本文介绍了如何在 react.js 中使用 Enter 键提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的表单和 onClick 方法.我想在按下键盘的 Enter 按钮时执行此方法.如何 ?

Here is my form and the onClick method. I would like to execute this method when the Enter button of keyboard is pressed. How ?

注意:不欣赏 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>

推荐答案

<button type="button" 更改为 <button type="submit".删除 onClick.而是执行 .这应该会捕获单击按钮并按下返回键.

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

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>

这篇关于如何在 react.js 中使用 Enter 键提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 18:36