在Typescript中反应事件类型

tBl*_*abs 15 typescript reactjs

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

private ButtonClickHandler(event: MouseEvent): void
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

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>'.`
Run Code Online (Sandbox Code Playgroud)

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

为什么?

摘自我的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"
  }
Run Code Online (Sandbox Code Playgroud)

编辑#1:

绑定render():

<button onClick={ this.ButtonClickHandler }>Toggle</button>
Run Code Online (Sandbox Code Playgroud)

constructor:

this.ButtonClickHandler = this.ButtonClickHandler.bind(this);
Run Code Online (Sandbox Code Playgroud)

小智 25

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

因此event: MouseEvent失败,因为onClick需要事件类型的专用版本.event: MouseEvent<HTMLElement>失败,因为它引用了错误的MouseEvent类型,没有类型参数的类型.React.MouseEvent<HTMLElement>因为你得到了正确的类型,给它所需的参数,结果类型与onClick处理程序兼容.

  • 谢谢也帮助了我。对于开箱即用的 typescript 和 React 来说,这样的基本问题都失败了,这似乎很遗憾。添加 onClick 事件需要这么多的 google fu 才能让它工作。 (2认同)

Mat*_*ell 21

我有同样的问题,但能够通过显式导入MouseEventfromReact

我有这个错误

import React from 'react';
Run Code Online (Sandbox Code Playgroud)

但是用这个解决了

import React, { MouseEvent } from 'react';
Run Code Online (Sandbox Code Playgroud)


tBl*_*abs 5

你不会相信它:将构造函数分配移动到渲染函数就足够了:

render()
{
return (
<button onClick={ this.Button_Click.bind(this) }>Toggle</button>
)}
Run Code Online (Sandbox Code Playgroud)

然后MouseEvent变得可用:

private Button_Click(event: MouseEvent): void
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?