# Type the onChange event of an element in React (TypeScript)
Type the onChange event of an element in React (TypeScript)
To type the onChange event of an element in React, set its type to
React.ChangeEvent<HTMLInputElement>
.
The ChangeEvent
type has a target
property that refers to the element. The
element’s value can be accessed on event.target.value
.
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); // 👇️ type as React.ChangeEvent<HTMLInputElement> // or React.ChangeEvent<HTMLTextAreaElement> (for textarea elements) const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setMessage(event.target.value); console.log(event.target.value); }; return ( <div> <input type="text" id="message" name="message" onChange={handleChange} value={message} /> </div> ); }; export default App;
We typed the event as React.ChangeEvent<HTMLInputElement>
because we’re typing
an onChange
event on an input element.
If you have a textarea
element, you would type the event as
React.ChangeEvent<HTMLTextAreaElement>
.
# The easiest way to find the type of an event
event
函数中的参数上。import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); // 👇️ event is written inline // hover over the `event` parameter with your mouse return ( <div> <input type="text" id="message" name="message" onChange={event => console.log(event)} value={message} /> </div> ); }; export default App;
event
参数上,它会显示事件的类型。TypeScript 能够在内联写入时推断事件的类型。
这非常有用,因为它适用于所有事件。只需编写内联事件处理程序的“模拟”实现,然后将鼠标悬停在event
参数上即可获取其类型。
键入文本区域元素的 onChange 事件
onChange
让我们看一个使用相同方法获取元素事件类型的示例
textarea
。
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); // 👇️ event is written inline // hover over the `event` parameter with your mouse return ( <div> <textarea id="message" name="message" onChange={event => console.log(event)} value={message} /> </div> ); }; export default App;
获取事件类型所需要做的onChange
就是 – 将其内联写入元素并将鼠标悬停在event
参数上。
现在我们有了类型,我们可以将事件处理程序提取到一个函数中并正确键入它。
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { setMessage(event.target.value); console.log(event.target.value); }; return ( <div> <textarea id="message" name="message" onChange={handleChange} value={message} /> </div> ); }; export default App;
onChange
只要您内联编写事件处理函数并将鼠标悬停在
event
参数上,TypeScript 就能够推断出事件的类型。
我还写了一篇关于
如何将 create-react-app 与 TypeScript 结合使用的详细指南。
额外资源
您可以通过查看以下教程来了解有关相关主题的更多信息: