window 上的 TypeScript 鼠标移动事件

TypeScript mousemove event on window

我正在尝试使用 React with TypeScript 在控制台中的 window 上记录 mousemove 上的事件。经过一些研究并查看了 ,我想我可以使用 MouseEvent 作为传递给侦听器的事件的类型。

useEffect(() => {
  const onMouseMove = (e: MouseEvent) => {
    e.preventDefault();
    console.log(e);
  };

  window.addEventListener("mousemove", onMouseMove);

  return () => {
    window.removeEventListener("mousemove", onMouseMove);
  };
}, []);

但是当运行时提示我如下错误:

const onMouseMove: (e: MouseEvent) => void
No overload matches this call.
  Overload 1 of 2, '(type: "mousemove", listener: (this: Window, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type '(this: Window, ev: MouseEvent) => any'.
      Types of parameters 'e' and 'ev' are incompatible.
        Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persist
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(e: MouseEvent) => void' is not assignable to type 'EventListener'.
        Types of parameters 'e' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 18 more

我尝试使用一些建议更新我的事件侦听器语法,但 none 似乎解决了问题。

const onMouseMove = (e: MouseEvent): any => {} // any as return type
const onMouseMove: EventListener = (e: MouseEvent) => {} // type as EventListener

请注意 React 有自己的 MouseEvent 定义(以及其他事件)

当您向 React Element 添加事件处理程序时,您必须使用 React Event

<div onClick={(e: React.MouseEvent) => { console.log(e) }></div>

但是如果您使用 DOM API 添加事件侦听器,请确保它来自 DOM

  // DOM Event not to be confused with React.MouseEvent
  const onMouseMove = (e: MouseEvent) => {
    e.preventDefault();
    console.log(e);
  };

  window.addEventListener("mousemove", onMouseMove);

  return () => {
    window.removeEventListener("mousemove", onMouseMove);
  };

TypeScript 支持 DOM 框的事件。如果您从 react

导入 Event
import { MouseEvent } from 'react';

这将覆盖 DOM 的 MouseEvent,并且 TypeScript 不会满意,因为这两种类型是不同的