在 React (TypeScript) 中输入 onKeyUp 事件
Type the onKeyUp event in React (TypeScript)
在 React 中使用React.KeyboardEvent<HTMLElement>
类型来键入 onKeyUp 事件。该KeyboardEvent
接口用于onKeyUp
事件。您可以访问用户按下的键的值作为event.key
.
import React from 'react'; const App = () => { // ✅ type event as React.KeyboardEvent<HTMLElement> const handleKeyUp = (event: React.KeyboardEvent<HTMLElement>) => { console.log(event.key); // console.log(event.code); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyUp={handleKeyUp} /> </div> ); }; export default App;
我们将事件键入为,React.KeyboardEvent<HTMLElement>
因为
KeyboardEvent类型用于onKeyUp
React 中的事件。
但是,我们可以在键入事件时更加具体。
event
函数中的参数上。const App = () => { // 👇️ onKeyUp event is written inline // hover over the `event` parameter with your mouse return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyUp={event => console.log(event)} /> </div> ); }; export default App;
event
参数上,它会显示事件的类型。TypeScript 能够在内联写入时推断事件的类型。
这非常有用,因为它适用于所有事件。只需编写内联事件处理程序的“模拟”实现,然后将鼠标悬停在event
参数上即可获取其类型。
现在我们知道onKeyUp
示例中事件的正确类型是
React.KeyboardEvent<HTMLInputElement>
,我们可以提取我们的处理函数。
import React from 'react'; const App = () => { const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => { console.log(event.key); // console.log(event.code); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyUp={handleKeyUp} /> </div> ); }; export default App;
对象的key
属性KeyboardEvent
返回用户按下的键的值。
The type we passed to the KeyboardEvent
generic is HTMLInputElement
because
we attached the onKeyUp
event to an input element, however you could be
attaching the event to a different element.
HTML***Element
. Once you start typing HTML..
, your IDE should be able to help you with autocomplete.Some commonly used types are: HTMLInputElement
, HTMLButtonElement
,
HTMLAnchorElement
, HTMLImageElement
, HTMLTextAreaElement
,
HTMLSelectElement
, etc.
onKeyUp
events.As long as you write the event handler function inline and hover over the
event
parameter, TypeScript will be able to infer the event’s type.