How to submit a form using Enter key in react.js?

前端 未结 6 427
野的像风
野的像风 2020-12-04 10:34

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

N.B: No jquery is appreciated.

6条回答
  •  温柔的废话
    2020-12-04 11:01

    Use keydown event to do it:

       input: HTMLDivElement | null = null;
    
       onKeyDown = (event: React.KeyboardEvent): 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 (
             
    this.input = node} />
    ); }

提交回复
热议问题