当我在事件处理程序中使用MouseEvent类型时,我无法构建我的React/类型记录应用程序:
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.。
为什么?
摘录自我的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()中的绑定
<button onClick={ this.ButtonClickHandler }>Toggle</button>在constructor中
this.ButtonClickHandler = this.ButtonClickHandler.bind(this);发布于 2017-10-18 19:38:45
我认为这里有两种不同的类型可用: jsx/lib/js/js/web.jsx中的MouseEvent (它没有类型参数)和@ React.MouseEvent<T> / are /index.d.ts(它有一个类型参数T,它来自的元素的类型)。类型记录使用结构分型,所以即使它们是不同的类型,它们也可以兼容。但是,为了与onClick处理程序兼容,您需要使用React的版本,并为T提供适当的类型(HTMLElement可以工作,或者如果您知道要将该处理程序附加到哪个元素,则可以更加具体)。
所以event: MouseEvent失败了,因为onClick需要事件类型的专门版本。event: MouseEvent<HTMLElement>失败是因为它引用了错误的MouseEvent类型,即没有类型参数的类型。React.MouseEvent<HTMLElement>之所以有效,是因为您获得了正确的类型,给出了它所需的参数,并且得到的类型与onClick处理程序兼容。
发布于 2019-11-29 11:43:45
我也有同样的问题,但是我能够通过从React导入React的解释性来修复它。
我犯了这个错误
import React from 'react';但是用这个解决了
import React, { MouseEvent } from 'react';发布于 2017-10-12 20:01:53
您不会相信它:移动构造函数辅助来呈现函数就足够了:
render()
{
return (
<button onClick={ this.Button_Click.bind(this) }>Toggle</button>
)}然后,MouseEvent变成了avaliable:
private Button_Click(event: MouseEvent): void为什么会发生这种事?
https://stackoverflow.com/questions/46524815
复制相似问题