在 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;
輸出
廣告