当我在事件处理程序中使用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.
。
为什么?
来自我的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);
(event: React.MouseEvent<HTMLButtonElement>)
? - JulChprivate ButtonClickHandler(event: React.MouseEvent<HtmlButtonElement>): void
应该可以工作。 - paibambooerror TS2304: 无法找到名称 'HtmlButtonElement'
和error TS2352: 类型 'MouseEvent<any>' 不能转换为类型 'MouseEvent'。属性 'fromElement' 在类型 'MouseEvent<any>' 中缺失
。 - tBlabs