【发布时间】:2023-01-22 04:15:39
【问题描述】:
我的项目需要你的帮助。
我想在单击外部时关闭菜单。
我写了下面的代码,但我遇到了打字稿的问题。
当我使用 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
有人能帮我吗?非常感谢 !
【问题讨论】:
-
你能提供一个minimal reproducible example吗?因为我无法重现您的问题,因为在我的情况下使用 MouseEvent 实际上有效
标签: reactjs typescript events mouseevent