在 React 中处理 onKeyPress 事件

在 React 中处理 onKeyPress 事件

Handle the onKeyPress event in React

onKeyPress在 React 中处理事件:

  1. onKeyPress在元素上设置道具。
  2. 使用对象的key属性event获取用户按下的键。
  3. 例如,if (event.key === 'Enter') {}
应用程序.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleKeyPress = 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} onKeyPress={handleKeyPress} onChange={event => setMessage(event.target.value)} /> </div> ); }; export default App;

反应处理 onkeypress 事件

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

对象的key
属性
event返回用户按下的键的值。

Every time the user presses a key, the handleKeyPress 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 don’t want to track the state of the input field, you can get its value
on the target property of the event object.

App.js
const App = () => { const handleKeyPress = event => { console.log(event.key); if (event.key === 'Enter') { console.log('✅ Enter key pressed'); } // 👇️ access input value from event object console.log(event.target.value); }; return ( <div> <input type="text" id="message" name="message" onKeyPress={handleKeyPress} /> </div> ); }; export default App;

Instead of storing the value of the input field, we get it using the event
object.

The target property on the event refers to the input element.

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