如何使用mouseEvent和www.example.com键入事件event.target(使用typescript响应项目)?

jhkqcmku  于 2023-01-27  发布在  TypeScript
关注(0)|答案(2)|浏览(136)

我的项目需要你的帮助。
我想在单击外部时关闭菜单。
我写了下面的代码,但是我的 typescript 有问题。
当我使用any输入"ev"参数时,代码可以工作,但我知道这不是推荐的。
这里我的代码:

useEffect(() => {
    const checkIfClickedOutside = (ev: any) => {
      if (isMenuOpen && menuRef.current && !menuRef.current?.contains(ev.target)) {
        setIsMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', checkIfClickedOutside);

    return () => {
      document.removeEventListener('mousedown', checkIfClickedOutside);
    };
  }, [isMenuOpen, menuRef]);

我尝试使用MouseEvent,但出现此错误:

Argument of type 'EventTarget' is not assignable to parameter of type 'Node'.
Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more.

还有这个

const checkIfClickedOutside: (ev: MouseEvent) => void
No overload matches this call.
  Overload 1 of 2, '(type: "mousedown", listener: (this: Document, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(ev: MouseEvent) => void' is not assignable to parameter of type '(this: Document, ev: MouseEvent) => any'.
      Types of parameters 'ev' 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 '(ev: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(ev: MouseEvent) => void' is not assignable to type 'EventListener'.
        Types of parameters 'ev' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 18 more

有人能帮帮我吗?谢谢!

qyyhg6bp

qyyhg6bp1#

当您使用带有mousedown参数addEventListener时,Official DOM typings指向MouseEvent接口。

92dk7w1h

92dk7w1h2#

如果您使用MouseEvent

import {MouseEvent} from "react"

您将得到该错误。相反,不要导入MouseEvent。使用全局可用的MouseEvent

相关问题