在 React (TypeScript) 中输入 onKeyPress 事件

在 React (TypeScript) 中输入 onKeyPress 事件

Type the onKeyPress event in React (TypeScript)

在 React 中使用React.KeyboardEvent<HTMLElement>类型来敲击 onKeyPress 事件。KeyboardEvent接口用于onKeyPress事件。您可以访问用户按下的键的值作为event.key.

应用程序.tsx
import React from 'react'; const App = () => { const handleKeyPress = (event: React.KeyboardEvent<HTMLElement>) => { console.log(event.key); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyPress={handleKeyPress} /> </div> ); }; export default App;

我们将事件键入为,React.KeyboardEvent<HTMLElement>因为
KeyboardEvent类型用于onKeyPressReact 中的事件。

但是,我们可以在键入事件时更加具体。

找出事件类型的最简单方法是内联编写事件处理程序并将鼠标悬停在event函数中的参数上。
应用程序.tsx
const App = () => { // 👇️ onKeyPress event is written inline // hover over the `event` parameter with your mouse return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyPress={event => console.log(event)} /> </div> ); }; export default App;

内联获取 onkeypress 事件的类型

When the event is written inline, I can hover over the event parameter and it shows me what the type of the event is.

TypeScript is able to infer the type of the event when it’s written inline.

This is very useful because it works with all events. Simply write a “mock”
implementation of your event handler inline and hover over the event parameter
to get its type.

Once you know what the type of the event is, you are able to extract your handler function and type it correctly.

Now that we know that the correct type for the onKeyPress event in the example
is React.KeyboardEvent<HTMLInputElement>, we can extract our handler function.

App.tsx
import React from 'react'; const App = () => { // ✅ type event correctly const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => { console.log(event.key); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyPress={handleKeyPress} /> </div> ); }; export default App;

The type we passed to the KeyboardEvent generic is HTMLInputElement because
we attached the onKeyPress event to an input element, however you could be
attaching the event to a different element.

The types are consistently named as 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.

Note that you can use this approach to get the type of all events, not just onKeyPress 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.