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

前端 未结 6 425
野的像风
野的像风 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 10:59

    It's been quite a few years since this question was last answered. React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.

    Now we can write this:

      useEffect(() => {
        const listener = event => {
          if (event.code === "Enter" || event.code === "NumpadEnter") {
            console.log("Enter key was pressed. Run your function.");
            // callMyFunction();
          }
        };
        document.addEventListener("keydown", listener);
        return () => {
          document.removeEventListener("keydown", listener);
        };
      }, []);
    

    This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.

    0 讨论(0)
  • 2020-12-04 11:00

    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>
    
    0 讨论(0)
  • 2020-12-04 11:01

    Use keydown event to do it:

       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>
          );
        }
    
    0 讨论(0)
  • 2020-12-04 11:12

    this is how you do it if you want to listen for the "Enter" key. There is an onKeydown prop that you can use and you can read about it in react doc

    and here is a codeSandbox

    const App = () => {
        const something=(event)=> {
            if (event.keyCode === 13) {
                console.log('enter')
            }
        }
    return (
        <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
            <input  type='text' onKeyDown={(e) => something(e) }/>
        </div>
    );
    }
    
    0 讨论(0)
  • 2020-12-04 11:17

    import React , {useEffect , useRef } from 'react' ; 
    
    function Example() {
    
     let inp = useRef() 
     useEffect(()=>{ 
       if (!inp && !inp.current) return 
       inp.current.focus() ; 
       return () => inp = null ;  
     });
     
     const handleSubmit = () => { 
        //...  
     }
    
     return ( 
        <form                                                        
        onSubmit={(e) => {                                       
          e.preventDefault();                                       
          handleSubmit(e);                               
            }}                                                        > 
            <input 
               name="fakename" 
               defaultValue="...." 
               ref={inp}
               type="text"
               style={{
                 position :"absolute" , 
                 opacity : 0  
               }}
             />
             <button type="submit"> 
                submit
             </button>
        </form>
     )
    }

    enter code heresometimes in popus it would not work to binding just a form and passing the onSubmit to the form because form may not have any input . in this cases if you bind the event to the document by doing document.addEventListener it will be cause problem in another parts of the application on count of this for solving thiis issue we should wrapp a form and should put a input with that is hidden by css .. then you foucus on that input by ref it will be work currectly .

    0 讨论(0)
  • 2020-12-04 11:20

    I've built up on @user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!

    const { useEffect } = require("react");
    
    const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
        useEffect(() => {
            //https://stackoverflow.com/a/59147255/828184
            const listener = (event) => {
                if (event.code === "Enter" || event.code === "NumpadEnter") {
                    handlePressEnter();
                }
            };
    
            document.addEventListener("keydown", listener);
    
            return () => {
                document.removeEventListener("keydown", listener);
            };
        }, []);
    
        const handlePressEnter = () => {
            //https://stackoverflow.com/a/54316368/828184
            const mouseClickEvents = ["mousedown", "click", "mouseup"];
            function simulateMouseClick(element) {
                mouseClickEvents.forEach((mouseEventType) =>
                    element.dispatchEvent(
                        new MouseEvent(mouseEventType, {
                            view: window,
                            bubbles: true,
                            cancelable: true,
                            buttons: 1,
                        })
                    )
                );
            }
    
            var element = document.querySelector(querySelectorToExecuteClick);
            simulateMouseClick(element);
        };
    };
    
    export default useEnterKeyListener;
    

    This is how you use it:

    useEnterKeyListener({
        querySelectorToExecuteClick: "#submitButton",
    });
    

    https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407

    0 讨论(0)
提交回复
热议问题