从React中导入事件类型(TypeScript)

21
如何从React中导入事件类型?
例如,如何导入KeyboardEvent以用于onKeyDown回调函数的类型注释?
我已经浏览了Material-ui .d.ts文件,并发现在该文件中使用的EventTypes是根据React定义的。
onKeyDown?: React.KeyboardEventHandler;

而在React .d.ts中

type KeyboardEventHandler = EventHandler<KeyboardEvent>;

但是我找不到一种方法来导入它们...

3个回答

40

对我来说它很好用:

handleKeyPress (event: React.KeyboardEvent): any {
}

而且我也使用了 material-ui


10
添加KeyboardEvent到你的React导入语句中。然后,在你的处理函数中,你可以使用KeyboardEvent类型。如果你没有在导入语句中指定它,你将使用ES5声明的KeyBoardEvent,这将无法编译你的React项目。
import React, { Component, KeyboardEvent } from "react";

export class MyInput extends Component{
...

  handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    console.log(e);
    // Do something here
  }

  render() {
      return (
        <input onKeyDown={this.handleKeyDown.bind(this}/>
      );
    }
  }
}

0
如果您在使用React 16.1+时遇到错误"KeyboardEvent requires type argument",您可以尝试以下方法:
private onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
   ... 
}

其中泛型参数是您元素的类型。


你可以这样做,但我不建议这样。TypeScript文档指出,除非你正在将JS项目迁移到TypeScript,否则不应使用any类型:https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#:~:text=any,every%20usage%20of%20the%20variable. - dading84
1
已经根据需要更新了我的答案。 - Damian Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接