小编典典

如何在react.js中使用Enter键提交表单?

reactjs

这是我的表单和onClick方法。我想在按下键盘的Enter按钮时执行此方法。怎么样 ?

注意: 没有jquery被赞赏。

 comment: function (e) {
        e.preventDefault();
        this.props.comment({comment: this.refs.text.getDOMNode().value, userPostId:this.refs.userPostId.getDOMNode().value})
    },


 <form className="commentForm">
     <textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text"  /><br />
    <input type="text" placeholder="userPostId" ref="userPostId" /> <br />
     <button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
    </form>

阅读 1105

收藏
2020-07-22

共1个答案

小编典典

更改<button type="button"<button type="submit"。删除onClick。反而做<form className="commentForm" onSubmit={this.onFormSubmit}>。这应该可以单击按钮并按回车键。

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>
2020-07-22