在 React 中处理 onKeyDown 事件

在 React 中处理 onKeyDown 事件

Handle the onKeyDown event in React

onKeyDown在 React 中处理事件:

  1. onKeyDown在元素上设置道具。
  2. 使用对象的key属性event获取用户按下的键。
  3. 例如,if (event.key === 'Enter') {}
应用程序.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyDown = event => { console.log(event.key); if (event.key === 'Enter') { console.log('✅ Enter key pressed'); } // 👇️ access input value from state // console.log(message); // 👇️ access input value from event object // console.log(event.target.value) }; return ( <div> <input type="text" id="message" name="message" value={message} onKeyDown={handleKeyDown} onChange={event => setMessage(event.target.value)} /> </div> ); }; export default App;

反应 onkeydown 事件

如果您需要onKeyDown在元素上设置事件侦听器,请向下滚动到下一个代码片段。 div

我们onKeyDown在元素上设置了 prop input,所以每次用户在input获得焦点时按下按钮,handleKeyDown都会调用该函数。

The key
property on the event object returns the value of the key pressed by the user.

Every time the user presses a key, the handleKeyDown function runs and we
check if the user pressed Enter.

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

If you need to set the onKeyDown event listener on a div element, set the
tabIndex prop on the element to make it focusable.

App.js
const App = () => { const handleKeyDown = event => { console.log('User pressed: ', event.key); }; return ( <div> <div tabIndex={0} onKeyDown={handleKeyDown}> <h2>Some content here</h2> </div> </div> ); }; export default App;

Div elements are not focusable by default, so in order to handle the onKeyDown
event on a div, we have to set the
tabIndex
prop on the element.

The tabIndex attribute indicates that its element can be focused and where it participates in sequential keyboard navigation (using the Tab key).

When an element’s tabIndex is set to 0, the element is focusable in
sequential keyboard navigation, after any positive tabIndex values.

For example, if other elements on the page have a tab index of 1, 2, 3, etc, an
element with a tabIndex of 0 would get focused after the elements with
positive tabIndex.

You could also set the element’s tabIndex to -1, which means that the
element is not reachable via sequential keyboard navigation (using the Tab
key), but can be focused with JavaScript or by clicking on it with the mouse.

发表评论