繁体   English   中英

React和Typescript:类型参数不能分配给'EventListenerOrEventListenerObject'类型的参数

[英]React and Typescript: Argument of type is not assignable to parameter of type 'EventListenerOrEventListenerObject'

我正在尝试将Typescript添加到我的React项目中:

componentDidMount() {
  document.addEventListener('mousemove', this.handleMouseMove);
}

private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => {
  appStore.updateSideWidth(e.pageX);
}

但是在this.handleMouseMove下出现以下错误:

[ts]
Argument of type '(e: MouseEvent<HTMLElement>) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(e: MouseEvent<HTMLElement>) => void' is not assignable to type 
'EventListenerObject'.
Property 'handleEvent' is missing in type '(e: MouseEvent<HTMLElement>) 
=> void'.

我试过了:

1)@ ts-ignore它有效,但是我不愿意这样做,因为这就是为什么我使用Typescript 2)使用类似的方法:

private handleMouseMove = (e: Event) => {
  appStore.updateSideWidth((e as React.MouseEvent<HTMLElement>).pageX);
}

但是出现一个错误,提示由于缺少altKey而无法将Event转换为MouseEvent类型。

谢谢您的帮助!

当您向document中添加事件侦听器时,事件e将不是React事件。 因此, e的类型将只是MouseEvent

尝试:

componentDidMount() {
  document.addEventListener('mousemove', this.handleMouseMove);
}

private handleMouseMove = (e: MouseEvent) => {
  appStore.updateSideWidth(e.pageX);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM