"removeEventListener"和"addEventListener"方法出现"No overload matches this call"错误提示。

8

我有一个类似这样定义的keydown处理函数:

 handleOnKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
    if (key.isEscape(e.key)) {
      stopEvent(e);
      this.props.handleClose(e);
    }
  }

然而,在我的代码的另一部分中,该函数被传递给removeEventListeneraddEventListener

componentDidMount () {
    const { current: modal } = this.modalRef;
    if (modal) {
      modal.addEventListener('keydown', this.handleOnKeyDown);
    }
  }

  componentWillUnmount () {
    const { current: modal } = this.modalRef;
    if (modal) {
      modal.removeEventListener('keydown', this.handleOnKeyDown);
    }
  }

我遇到以下 TypeScript 错误:

No overload matches this call.
  Overload 1 of 2, '(type: "keydown", listener: (this: HTMLDivElement, ev: KeyboardEvent) => any, options?: boolean | EventListenerOptions | undefined): void', gave the following error.
    Argument of type '(e: React.KeyboardEvent<HTMLButtonElement>) => void' is not assignable to parameter of type '(this: HTMLDivElement, ev: KeyboardEvent) => any'.
      Types of parameters 'e' and 'ev' are incompatible.
        Type 'KeyboardEvent' is missing the following properties from type 'KeyboardEvent<HTMLButtonElement>': locale, nativeEvent, isDefaultPrevented, isPropagationStopped, persist
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions | undefined): void', gave the following error.
    Argument of type '(e: React.KeyboardEvent<HTMLButtonElement>) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(e: React.KeyboardEvent<HTMLButtonElement>) => void' is not assignable to type 'EventListener'.
        Types of parameters 'e' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'KeyboardEvent<HTMLButtonElement>': altKey, charCode, ctrlKey, getModifierState, and 12 more.ts(2769)

有什么解决方法?

你需要展示这个函数被传递到removeEventListener和addEventListener中的位置 - Jaromanda X
2
然而,错误信息很清楚.... 类型为'(e: React.KeyboardEvent<HTMLButtonElement>) => void'的参数无法分配给类型为'(this: HTMLDivElement, ev: KeyboardEvent) => any'的参数。 - Jaromanda X
1
正如jaromanda所暗示的那样,该错误使得您似乎正在将事件监听器分配给不适当的HTML元素。 - Andrew
这个回答解决了你的问题吗?react typescript issue on addEvenListener - Heretic Monkey
1个回答

2
问题似乎已经在这个问题中得到了回答: react typescript issue on addEvenListener addEventListenerremoveEventListener的处理函数不接受React.KeyboardEvent作为参数。它需要一个DOM事件。

有没有解决方案? - U4EA
只需使用 e: KeyboardEvent,而不是 React.KeyboardEvent。 - Ilija Lončarević
@IlijaLončarević 谢谢,它有效! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接