首页 > 解决方案 > 在 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();
  }}
/>

标签: javascriptreactjstypescript

解决方案


首先,正如 Bao Huynh Lam 在评论中所说,你需要使用这个

onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => {

作为事件的类型。然后,为了取输入的值,你可以强制转换e.targetHTMLInputElement,然后得到它的值。

检查这个小沙箱

<input
  type="text"
  placeholder="Search for claim ID"
  onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => {
    console.info((e.target as HTMLInputElement).value);
  }}
/>

推荐阅读