简体   繁体   English

在反应路由器组件中本地监听按键/按键事件

[英]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.我想在本地 react-router 组件中监听 keydown 事件,如果按下某个键,它将运行 function。 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.但是因为事件侦听器被添加到文档 object,如果我在不同的页面上,它仍然会尝试运行 function,导致错误,因为 function 是我的组件的本地。

For example if I am in login page (domain.com/login), the login page component loads in <main> , and <header> remains constant.例如,如果我在登录页面 (domain.com/login) 中,登录页面组件加载到<main>中,并且<header>保持不变。 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.所以我想在我的登录组件中运行一个 function,当这个人按下 Enter 时,它将按下登录按钮/也就是运行登录 function,它在按下按钮时被调用。

The return keyword will run when the component unmounts return 关键字将在组件卸载时运行

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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