【问题标题】:React + TypeScript反应 + 打字稿
【发布时间】:2019-07-11 02:41:17
【问题描述】:

我正在尝试为onKeyPress 事件编写一个类型正确的回调函数。

我尝试为函数或事件提供各种类型,但我似乎无法让事件e 被识别为同时具有key 字段和target.value 字段。


案例一:

 const onKeyPress: React.KeyboardEventHandler = async (e) => {
     if (e.key === "Enter") {
         console.log(e.target.value);
     }
 };

消息:

TS2339:“EventTarget”类型上不存在属性“值”。

案例2:

 const onKeyPress = async (e: React.KeyboardEvent<HTMLInputElement>) => {
     if (e.key === "Enter") {
         console.log(e.target.value);
     }
 };

消息:

TS2339:“EventTarget”类型上不存在属性“值”。

案例3:

事实证明,即使编写这个简单的 JSX 也会抛出同样的错误:

 <input type="text" onKeyPress={(e) => {
     const key = e.key;
     const val = e.target.value;
 }}/>

环境

来自package.json

"@types/react": "^16.8.3"

“反应”:“^16.8.2”

"react-dom": "^16.8.2"

TypeScript 3.2.1.

有什么线索吗?

更新

接受的答案使我找到了这段工作代码:

 const onKeyPress = async (e: React.KeyboardEvent<HTMLInputElement>) => {
     if (e.key === "Enter") {
         console.log(`Received: ${e.currentTarget.value}`);
         await doAsyncStuff(e.currentTarget.value);
     }
 };

【问题讨论】:

    标签: reactjs typescript-typings


    【解决方案1】:

    Typescript 就在这里,值不存在于任何 html 元素上。您需要更准确地了解它是什么类型的元素。

    如果您将活动替换为

    React.KeyboardEvent<HTMLInputElement>
    

    它应该可以工作。

    您还需要使用event.currentTarget 而不是target

    【讨论】:

    • 也试过了,更新 OP 以反映这一点。
    • 看起来像event.currentTarget 你提到的事件类型成功了。我之前尝试过event.currentTarget,但我一定是在事件中应用了其他类型,但它失败了。现在可以了。接受为正确答案。
    • React 重用事件,因此您无法以异步方式访问它们,我认为这可能不适用于 await。
    • 我用我正在运行的最终和工作代码更新了 OP。感谢您的帮助。
    【解决方案2】:

    试试……

     const onKeyPress = async (e: React.KeyboardEvent<FormControl>) => {
          console.log(e.target.value);
     };
    

     const onKeyPress = async (e: KeyboardEventHandler<FormControl>) => {
         console.log(e.target.value);
     };
    

    Typescript/React what's the correct type of the parameter for onKeyPress?

    【讨论】:

      【解决方案3】:

      target 属性是指发生事件的元素,而不是附加处理程序的元素。这就是为什么它只有所有事件共有的属性,而value 不是其中之一。

      要访问value 属性,您需要从currentTarget 属性中获取它。

      您可以在React's type definition file 中看到此行为。

      /**
       * currentTarget - a reference to the element on which the event listener is registered.
       *
       * target - a reference to the element from which the event was originally dispatched.
       * This might be a child element to the element on which the event listener is registered.
       * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
       */
      

      【讨论】:

        猜你喜欢
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2019-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多