Reactjs Typescript中的React事件类型

Reactjs Typescript中的React事件类型,reactjs,typescript,Reactjs,Typescript,在我的事件处理程序中使用MouseEventtype时,我无法生成我的React/Typescript应用程序: private ButtonClickHandler(event: MouseEvent): void { ... } 我得到: error TS2322: Type '{ onClick: (event: MouseEvent) => void; children: string; }' is not assignable to type 'DetailedHTML

在我的事件处理程序中使用
MouseEvent
type时,我无法生成我的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>'.`
编辑#1:

render()中绑定


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

render()
{
return (
<button onClick={ this.Button_Click.bind(this) }>Toggle</button>
)}

为什么会发生这种情况?

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


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

我也遇到了同样的问题,但可以通过从
React
中明确导入
MouseEvent
来修复它

我犯了这个错误

import React from 'react';
import React, { MouseEvent } from 'react';
但这是固定的

import React from 'react';
import React, { MouseEvent } from 'react';

您能告诉我们您将这个处理程序绑定到元素的代码吗?我认为可能是这个问题的根本原因。你是说渲染和构造函数中的绑定?在编辑中添加了#1Did you try
(事件:React.MouseEvent)
?是的,效果相同。似乎其他人没有这样的问题:
private按钮clickhandler(事件:React.MouseEvent):void
应该工作谢谢你也帮了我。对于带有react的开箱即用的typescript来说,这样的基本问题失败了,这似乎是一个遗憾。添加onClick事件需要如此多的googlefu才能使其正常工作。
import React from 'react';
import React, { MouseEvent } from 'react';