在 React.js 中检测何时按下 Esc 键
Detect when the Esc key is pressed in React.js
在 React.js 中检测何时按下 Esc 键:
- 向元素添加
keydown
事件侦听document
器。 - 当用户按下一个键时,检查该键是否为
Esc
。 - 如果按下的键是 ,则调用一个函数或运行一些逻辑
Escape
。
应用程序.js
import {useEffect} from 'react'; const App = () => { const myFunction = () => { // your logic here console.log('pressed Esc ✅'); }; useEffect(() => { const keyDownHandler = event => { console.log('User pressed: ', event.key); if (event.key === 'Escape') { event.preventDefault(); // 👇️ your logic here myFunction(); } }; document.addEventListener('keydown', keyDownHandler); // 👇️ clean up event listener return () => { document.removeEventListener('keydown', keyDownHandler); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }; export default App;
我们使用useEffect
挂钩向元素添加keydown
事件侦听document
器。
现在每次用户按下一个键时,keyDownHandler
都会调用该函数。
The key
property on the KeyboardEvent
object returns the value of the key that was
pressed by the user.
In the function, we simply check if the user pressed the Esc
key and if they
did, we call a function.
The function we returned from the
useEffect
hook is used to clean up the event listener when the component unmounts.You should always clean up any event listeners you set up to avoid memory leaks
in your application.
We added the
keydown
event to the document
element, so the event will get triggered as long as the document has focus.This approach can be used to close pop-up menus, modals, or run any other custom
logic.
You can view the possible keys the user might press by visiting this
MDN page.
该条件if (event.key === 'Escape') {}
涵盖所有操作系统 – Windows、Mac、Linux、Android 等。