从 React (TypeScript) 导入事件类型

import Event Types from React (TypeScript)

如何从 React 导入事件类型?

举个例子,如何导入 KeyboardEvent 以便它可以用于 onKeyDown 回调类型注释?

我浏览了 Material-ui .d.ts 文件,发现在该文件中使用了 React

中定义的事件类型
onKeyDown?: React.KeyboardEventHandler;

在 React 中。d.ts

type KeyboardEventHandler = EventHandler<KeyboardEvent>;

但我找不到使用导入它们的方法...

它对我来说很好用:

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

我也用material-ui

如果您在 React 16.1+ 中收到错误“KeyboardEvent requires type argument”,您可以执行以下操作:

private onKeyDown = (event: React.KeyboardEvent<any>) => { ... }

KeyboardEvent 添加到您的 React 导入语句中。然后,在您的处理程序中,您可以使用 KeyboardEvent 类型。如果你没有在import语句中指定它,你将使用KeyBoardEvent的ES5声明,它不会与你的反应项目一起编译。

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}/>
      );
    }
  }
}