javascript - 在 React TypeScript 中键入输入的 keyup
问题描述
我正在尝试将我的 keyup 事件与 TS 一起使用,但使用any|KeyboardEvent
不起作用。
如何在 React 中键入事件?
TS 错误
Type '(e: KeyboardEvent) => void' is not assignable to type 'KeyboardEventHandler<HTMLInputElement>'.
Types of parameters 'e' and 'event' are incompatible.
Type 'KeyboardEvent<HTMLInputElement>' is missing the following properties from type 'KeyboardEvent': char, isComposing, DOM_KEY_LOCATION_LEFT, DOM_KEY_LOCATION_NUMPAD, and 15 more. TS2322
零件
<input
type="text"
placeholder="Search for claim ID"
onKeyUp={(e: KeyboardEvent) => {
console.info();
}}
/>
解决方案
首先,正如 Bao Huynh Lam 在评论中所说,你需要使用这个
onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => {
作为事件的类型。然后,为了取输入的值,你可以强制转换e.target
为HTMLInputElement
,然后得到它的值。
检查这个小沙箱
<input
type="text"
placeholder="Search for claim ID"
onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => {
console.info((e.target as HTMLInputElement).value);
}}
/>
推荐阅读
- apache-spark-sql - spark sql:选择 DecimalType 列的比例大于数字的行
- odoo-12 - 如何解决“Uncaught TypeError: Cannot read property 'type' of undefined when add button to tree view of Odoo”?
- javascript - 为什么从轮播内部元素的事件调用Bootstrap 4轮播暂停功能时不起作用?
- powershell - PowerShell 数组问题与变量
- maven - 如何在 Maven 中自定义 JMeter 报告以显示 Pass-Fail 而不是 OK-KO/在报告中添加更多静态值?
- release - 如果您的应用程序频繁更改,您如何让呼叫中心操作员保持最新状态?
- azure - 能否通过 Azure 防火墙路由点到站点流量?
- python - 高效的条件滚动计算 Pandas
- javascript - 当状态改变时,React 不会重新渲染我的组件
- mysql - SQL。如何找出哪些时间重叠?