【问题标题】:"No overload matches this call" for removeEventListener and addEventListenerremoveEventListener 和 addEventListener 的“没有重载匹配此调用”
【发布时间】:2020-04-27 14:53:47
【问题描述】:

我有一个如下定义的 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 的位置
  • 但是,错误信息很清楚....Argument of type '(e: React.KeyboardEvent&lt;HTMLButtonElement&gt;) =&gt; void' is not assignable to parameter of type '(this: HTMLDivElement, ev: KeyboardEvent) =&gt; any'.
  • 正如 jaromanda 所暗示的那样,该错误使您看起来像是将事件侦听器分配给了不适当的 HTML 元素
  • 这能回答你的问题吗? react typescript issue on addEvenListener

标签: reactjs typescript dom-events typescript-typings


【解决方案1】:

这个问题似乎可以回答这个问题: react typescript issue on addEvenListener

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

【讨论】:

  • 有什么解决办法吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-22
  • 1970-01-01
  • 2021-11-15
  • 2021-11-01
  • 1970-01-01
  • 2021-02-10
  • 2020-02-17
  • 2020-03-28
相关资源
最近更新 更多