reactjs - 如何使用 mouseEvent 和 event.target 键入事件(使用 typescript react 项目)?

标签 reactjs typescript events mouseevent

我的项目需要你的帮助。
我想在单击外部时关闭菜单。
我编写了以下代码,但 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

有人可以帮助我吗?非常感谢!

最佳答案

Official DOM typings指向MouseEvent当您将 addEventListenermousedown 参数一起使用时的接口(interface)。

关于reactjs - 如何使用 mouseEvent 和 event.target 键入事件(使用 typescript react 项目)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70758654/

相关文章:

reactjs - 使用 Jest 在 React Native 中模拟 Child

Angular2 组件无法通过服务中的 observable 进行通信

javascript - 捕获 beforeunload 确认已取消?

javascript - TypeScript:使用扩展运算符指定值必须在数组中

python - wxPython:绑定(bind)wx.EVT_CHAR_HOOK禁用TextCtrl退格键

javascript - 上传图片时如何传递参数?

reactjs - react 。您不应在 <Router> 之外使用 <withRouter(App)/>

reactjs - React : How to wrap component with HOC?(跨组件访问登录属性)

javascript - 使用 useEffect 的 React 组件中的内存泄漏

node.js - 没有为使用 nyc 的 vscode 扩展生成覆盖信息