Подтвердить что ты не робот

Как отправить форму с помощью клавиши Enter в файле response.js?

Вот моя форма и метод onClick. Я хотел бы выполнить этот метод, когда нажата клавиша Enter на клавиатуре. Как?

N.B: нет 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>
4b9b3361

Ответ 1

Измените <button type="button" на <button type="submit". Снимите onClick. Вместо этого сделайте <form className="commentForm" onSubmit={this.onCommentSubmit}>. Это должно поймать нажатие кнопки и нажатие клавиши возврата.

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>

Ответ 2

Используйте событие keydown чтобы сделать это:

   input: HTMLDivElement | null = null;

   onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
      // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopPropagation();
        this.onSubmit();
      }
    }

    onSubmit = (): void => {
      if (input.textContent) {
         this.props.onSubmit(input.textContent);
         input.focus();
         input.textContent = '';
      }
    }

    render() {
      return (
         <form className="commentForm">
           <input
             className="comment-input"
             aria-multiline="true"
             role="textbox"
             contentEditable={true}
             onKeyDown={this.onKeyDown}
             ref={node => this.input = node} 
           />
           <button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
         </form>
      );
    }