简体   繁体   中英

Listen for keypress / keydown event locally in react router component

I want to listen to keydown event in a local react-router component and it will run a function if a certain key was pressed. But because the event listener is added to document object, if I'm on a different page it will still try to run the function, resulting in error since the function is local to my component.

For example if I am in login page (domain.com/login), the login page component loads in <main> , and <header> remains constant. And so I want to run a function which is in my login component, when the person presses Enter, it will press the login button / aka run the login function which is called when the button is pressed.

The return keyword will run when the component unmounts

useEffect(() => {
    function onKeyDown(e) {
        if (e.key === "Enter") {
            console.log("ENTER PRESSED")
            submit()
        }
    }
    
    document.addEventListener("keydown", onKeyDown) 

    return () => document.removeEventListener('keydown', onKeyDown);
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM