当我使用 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/