首页 > 解决方案 > 由于 React Typescript 中的类型错误,将事件作为 typescript 中的参数传递失败

问题描述

我正在尝试将此事件传递给我的类型脚本文件中的事件侦听器,但是事件侦听器不允许传递任何其他事件类型,除了 Event、MouseEvent 和其他一些类型。

public componentDidMount() {
    const app = document.querySelector(".app");
    app.addEventListener("click", ((event: React.SyntheticEvent<HTMLElement>) => {
      this._handleWhiteSpaceEvent(event);
    }) as EventListener);
  }

事件侦听器不断抛出错误
Conversion of type '(event: React.SyntheticEvent<HTMLElement>) => void' to type 'EventListener' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of parameters 'event' and 'evt' are incompatible
或者当我尝试 React.MouseEvent
Conversion of type '(event: React.MouseEvent<HTMLElement>) => void' to type 'EventListener' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of parameters 'event' and 'evt' are incompatible.

有人能帮忙吗?

标签: reactjstypescriptaddeventlistenerevent-listenerreact-typescript

解决方案


当您直接在元素上设置事件侦听器时app,您获得的事件不是React.SyntheticEvent. 这只是定义中的MouseEvent常规lib.dom.tsonClick在 DOM 节点上设置属性时,您会收到一个合成事件。

您需要确保您有一个有效的app元素,而不是null因为document.querySelector不能保证找到结果。

Event您可以通过可选链接获得公正。

app?.addEventListener("click", (event: Event) => {
  this._handleWhiteSpaceEvent(event);
});

为了使用该MouseEvent类型,您必须细化appfromElement到的类型HTMLElement

if (app instanceof HTMLElement) {
  app.addEventListener("click", (event: MouseEvent) => {
    this._handleWhiteSpaceEvent(event);
  });
}

这些类型都不像 React 事件类型那样通用。通过 JSX 设置事件侦听器,您可以通过更少的检查获得更多信息。


推荐阅读