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

前端 未结 6 434
野的像风
野的像风 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.

提交回复
热议问题