[英]Why doesn't React.js fire onKey* event handlers for the Escape key?
顯然,如果按下的鍵是Escape
並且焦點位於輸入元素上,React 不會觸發 onKey* 事件處理程序(例如onKeyDown
和onKeyPress
)。 換句話說,當焦點位於此組件中的輸入元素上時,當我按下 Escape 鍵時,控制台上不會打印任何內容:
const Input = () => {
return (
<input
type="text"
value={...}
onChange={...}
onKeyDownCapture={(e) => {
if (e.key === "Escape") {
console.log("onKeyDownCapture: ", e);
}
}}
onKeyDown={(e) => {
if (e.key === "Escape") {
console.log("onKeyDownCapture: ", e);
}
}}
onKeyPress={(e) => {
if (e.key === "Escape") {
console.log("onKeyDownCapture: ", e);
}
}}
onKeyUp={(e) => {
if (e.key === "Escape") {
console.log("onKeyDownCapture: ", e);
}
}}
/>
);
};
這是為什么?
React 的合成事件支持的KeyboardEvent
類型的名稱是:
onKeyDown onKeyPress onKeyUp
我沒有確定您在訪問 CodeSandbox 鏈接時描述的問題,但這里有一個示例,它演示了一個記錄事件type
和綁定到每個事件的key
的單個偵聽器,以便您進行試驗/探索和重現成功在您的代碼中:
<div id="root"></div><script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.18.11/babel.min.js"></script> <script type="text/babel" data-type="module" data-presets="env,react"> const logKeyboardEventMeta = (ev) => console.log(ev.type, JSON.stringify(ev.key)); function Input () { return ( <input type="text" onKeyDown={logKeyboardEventMeta} onKeyPress={logKeyboardEventMeta} onKeyUp={logKeyboardEventMeta} /> ); } const reactRoot = ReactDOM.createRoot(document.getElementById('root')); reactRoot.render( <React.StrictMode> <Input /> </React.StrictMode> ); </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.