在 ReactJS 中使用 onKeyPress 事件
在本文中,我们将了解如何访问用户在 React 应用程序中按下的键码
要检测用户从其键盘按下的键码或键,那么 React 就为此准备了一个预定义的 onKeyPress 事件。虽然对于 ALT、CTRL、SHIFT、ESC 等所有键都不会触发它,但它可以正确地检测其他键。
事件触发的顺序是 -
onKeyDown - 在用户按下键时触发
onKeyPress - 在用户按住键时触发
onKeyUp - 在用户释放键时触发
示例
在此示例中,我们将构建一个具有某些预定义功能的 React 应用程序,并在按下特定键时执行特定任务。为此,每次单击按钮时,都会触发 onkeyButton,然后将比较其键码并执行指定的任务。
App.jsx
import React, { useState } from 'react';
const App = () => {
const [email, setEmail] = useState(null);
const [pass, setPass] = useState(null);
const handler = (event) => {
if (event.key === 'e') {
setEmail('qwerty@gmail.com');
} else {
setPass('qwerty');
}
};
return (
<div>
<h1>Tutorialspoint</h1>
<p>Username: Rahul Bansal </p>
<ol>
<li>Press e to fetch email</li>
<li>Press p to fetch password</li>
</ol>
{email ? <p>Email: {email}</p> : null}
{pass ? <p>Password: {pass}</p> : null}
<input
placeholder="Press key"
type="text"
onKeyPress={(e) => handler(e)}
/>
</div>
);
};
export default App;输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP