React应用Onclick Event报错:Typescript MouseEvent事件类型不兼容求助
报错信息
Types of parameters 'event' and 'event' are incompatible. Type 'MouseEvent<HTMLElement, MouseEvent>' is not assignable to type 'MouseEvent<HTMLButtonElement, MouseEvent>'. Types of property 'currentTarget' are incompatible. Type 'EventTarget & HTMLElement' is not assignable to type 'EventTarget & HTMLButtonElement'. Type 'EventTarget & HTMLElement' is missing the following properties from type 'HTMLButtonElement': disabled, form, formAction, formEnctype, and 13 more. TS2322 160 | variant="outline-secondary" 161 | className="search-button" > 162 | onClick={(event: React.MouseEvent<HTMLButtonElement>) => | ^ 163 | this.onSearch(event) 164 | } 165 | >
错误原因
该报错是因为你给onClick事件参数手动指定的React.MouseEvent<HTMLButtonElement>类型,和当前绑定事件的组件实际抛出的事件类型不匹配:你绑定事件的组件并非原生<button>标签(多数是封装后的通用UI组件),它默认抛出的点击事件目标类型是通用HTMLElement,两者currentTarget属性的属性集合不一致,触发TypeScript类型校验失败。
解决方法
- 方案1:调整为通用事件类型
如果你的点击处理逻辑不需要用到HTMLButtonElement独有的属性(比如disabled、form、formAction等),直接把事件参数类型改为通用HTMLElement即可:
// 绑定事件处修改类型 onClick={(event: React.MouseEvent<HTMLElement>) => this.onSearch(event)}
同步修改onSearch方法的入参类型保持一致即可。
- 方案2:使用类型断言对齐类型
如果你确定该组件最终渲染的就是原生button元素,且需要用到button专属属性,可以通过类型断言强制匹配类型:
onClick={(event: React.MouseEvent<HTMLElement>) => { this.onSearch(event as React.MouseEvent<HTMLButtonElement>) }}
- 方案3:指定组件渲染的原生标签
如果你使用的是第三方UI库组件,可查看组件是否支持as属性指定渲染的原生标签,指定为button后事件类型通常会自动匹配:
<Button variant="outline-secondary" className="search-button" as="button" onClick={(event: React.MouseEvent<HTMLButtonElement>) => this.onSearch(event)} >
内容的提问来源于stack exchange,提问作者lukeharg
相关产品推荐
相关产品推荐

