在 React 中处理 onKeyPress 事件
Handle the onKeyPress event in React
onKeyPress
在 React 中处理事件:
onKeyPress
在元素上设置道具。- 使用对象的
key
属性event
获取用户按下的键。 - 例如,
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
在元素上设置了 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.