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

时间:2018-05-15 05:21:02

标签: reactjs typescript

我正在尝试将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-忽略它有效,但我不愿意这样做,因为这就是我使用Typescript的原因 2)使用类似的东西:

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

但是由于缺少altKey而得到错误,因此无法将事件转换为MouseEvent类型。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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

尝试:

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

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