reactjs - Typescript 中的 React 事件类型

标签 reactjs typescript

当我使用 MouseEvent 时,我无法构建我的 React/Typescript 应用程序输入我的事件处理程序:

private ButtonClickHandler(event: MouseEvent): void
{
    ...
}

我得到:

error TS2322: Type '{ onClick: (event: MouseEvent) => void; children: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'.
  Type '{ onClick: (event: MouseEvent) => void; children: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'.
    Types of property 'onClick' are incompatible.
      Type '(event: MouseEvent) => void' is not assignable to type 'EventHandler<MouseEvent<HTMLButtonElement>>'.
        Types of parameters 'event' and 'event' are incompatible.
          Type 'MouseEvent<HTMLButtonElement>' is not assignable to type 'MouseEvent'.
            Property 'fromElement' is missing in type 'MouseEvent<HTMLButtonElement>'.`

我也试过MouseEvent<HTMLButtonElement>但后来我得到了error TS2315: Type 'MouseEvent' is not generic. .

为什么?

摘 self 的package.json :

 "devDependencies": {
    "@types/react": "^16.0.7",
    "@types/react-dom": "^15.5.5",
    "ts-loader": "^2.3.7",
    "typescript": "^2.5.3",
    "webpack": "^3.6.0"
  },
  "dependencies": {
    "react": "^16.0.0",
    "react-dom": "^16.0.0"
  }

编辑#1:

render() 中绑定(bind):

<button onClick={ this.ButtonClickHandler }>Toggle</button>

constructor :

this.ButtonClickHandler = this.ButtonClickHandler.bind(this);

最佳答案

我认为这里发生的是有两种不同的类型可用:MouseEvent来自 jsx/lib/js/js/web.jsx(没有类型参数)和 React.MouseEvent<T>来自@types/react/index.d.ts(它有一个类型参数,T,它来自的元素的类型)。 typescript 使用 structural typing ,因此即使它们是不同的类型,它们也可以兼容。但是为了兼容onClick您需要使用 React 版本的处理程序,并为 T 提供适当的类型( HTMLElement 会起作用,或者如果您知道要将此处理程序附加到哪个元素,则可以更具体)。

所以 event: MouseEvent失败,因为 onClick需要事件类型的专门版本。 event: MouseEvent<HTMLElement>失败,因为它引用了错误的 MouseEvent类型,没有类型参数的类型。 React.MouseEvent<HTMLElement>之所以有效,是因为您获得了正确的类型,为其提供了所需的参数,并且生成的类型与 onClick 兼容。处理程序。

关于reactjs - Typescript 中的 React 事件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46524815/

相关文章:

reactjs - JSDOM:无法解析 CSS 样式表

reactjs - Typescript 和 React,React.KeyboardEvent<HTMLInputElement> 的编译时和运行时之间的不同类型

javascript - 如何获取Draft.js中Editor的onChange事件?

javascript - 使用 redux-toolkit 和 createAsyncThunk() 完成操作后如何导航?

javascript - Mongoose : "TypeError: "监听器“参数必须是一个函数”连接

javascript - 如何访问 .find 方法中的索引

node.js - Mongoose + Typescript -> 导出模型接口(interface)

angular - 两个子组件共享控制权

javascript - mapStateToProps 从 reducer 返回未定义的状态

javascript - 调用jsPDF的save方法时获取TypeError Arg 1