在 React.js 中检测何时按下 Enter 或 Escape 键

目录

Detect when the Enter key is pressed in React.js

  1. 在 React.js 中检测何时按下 Enter 键
  2. 在 React.js 中检测何时按下 Esc 键

如果您需要检测何时按下Esc键,请单击第二个副标题。

在 React.js 中检测何时按下 Enter 键

在 React.js 中检测何时按下 Enter 键:

  1. keydown向元素添加事件侦听器document
  2. 当用户按下一个键时,检查该键是否为Enter
  3. 如果按下的键是 ,则调用一个函数或运行一些逻辑Enter
应用程序.js
import {useEffect} from 'react'; const App = () => { const myFunction = () => { // your logic here console.log('pressed Enter ✅'); }; useEffect(() => { const keyDownHandler = event => { console.log('User pressed: ', event.key); if (event.key === 'Enter') { event.preventDefault(); // 👇️ your logic here myFunction(); } }; document.addEventListener('keydown', keyDownHandler); return () => { document.removeEventListener('keydown', keyDownHandler); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }; export default App;
如果您需要检测Enter用户在字段中键入时何时按下键input,请向下滚动到下一个代码片段。

我们使用useEffect
挂钩向元素添加
keydown事件侦听器document

现在每次用户按下一个键时,keyDownHandler都会调用该函数。

检测回车

在函数中,我们简单地检查用户是否按下了Enter键,如果按下了,我们调用一个函数。

我们从钩子返回的函数useEffect用于在组件卸载时清理事件监听器。

检测用户在键入#时按下 Enter 键

要检测用户在输入字段中键入时何时按下 Enter 键:

  1. onKeyDown道具添加到input元素。
  2. 每次用户在输入字段中按下一个键时,检查按下的键是否为 Enter。
应用程序.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log('User pressed: ', event.key); if (event.key === 'Enter') { // 👇️ your logic here console.log('Enter key pressed ✅'); } }; return ( <div> <input onChange={event => setMessage(event.target.value)} onKeyDown={handleKeyDown} id="message" name="message" /> </div> ); }; export default App;

onKeyDownprop 被添加到一个input字段时,我们只监听用户在输入字段获得焦点时按下的键。

这与之前的代码片段不同,我们在该代码片段中添加了
元素
keydown上的事件侦听器document

检测进入按下输入字段

当我们需要在用户完成输入并且不想使用带有onSubmit事件处理程序的表单时运行一些逻辑时,这种方法很有用。

您可以通过访问此MDN 页面查看用户可能按下的键

该条件if (event.key === 'Enter') {}涵盖所有操作系统 – Windows、Mac、Linux、Android 等。

在 React.js 中检测何时按下 Esc 键

To detect when the Esc key is pressed in React.js:

  1. Add a keydown event listener to the document element.
  2. When the user presses a key, check if the key is Esc.
  3. Invoke a function or run some logic if the pressed key is Escape.
App.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;

We used the useEffect
hook to add a keydown event listener to the document element.

Now every time the user presses a key, the keyDownHandler function is invoked.

检测逃逸新闻

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 and modals or run any other
custom logic.

You can view the possible keys the user might press by visiting this
MDN page.

The condition if (event.key === 'Escape') {} covers all operating systems –
Windows, Mac, Linux, Android, etc.