本文介绍了对于emoveEventListener和addEventListener,没有重载与此调用匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按键处理函数,定义如下:

 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);
    }
  }

我收到以下打字稿错误:

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)

如何解决此问题?

推荐答案

该问题似乎已回答以下问题:react typescript issue on addEvenListener

addEventListenerremoveEventListener的处理函数不接受React.KeyboardEvent作为参数。它需要一个DOM事件。

这篇关于对于emoveEventListener和addEventListener,没有重载与此调用匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:14