typescript 如何输入点击事件文档?

hgb9j2n6  于 2023-02-05  发布在  TypeScript
关注(0)|答案(1)|浏览(240)

打印脚本代码

type PopupClick = MouseEvent & {
            path: Node[];
    };

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            const _event = event as PopupClick;
            console.log(_event);
            if (
                selectorRef.current &&
                !_event.path.includes(selectorRef.current)
            ) {
                setIsVisible(false);
            }
        };

        document.addEventListener("click", handleClickOutside);
        return () => document.removeEventListener("click", handleClickOutside);
    }, []);

错误文本

const handleClickOutside: (event: MouseEvent) => void
No overload matches this call.
  Overload 1 of 2, '(type: "click", listener: (this: Document, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(event: MouseEvent) => void' is not assignable to parameter of type '(this: Document, ev: MouseEvent) => any'.
      Types of parameters 'event' and 'ev' are incompatible.
        Type 'MouseEvent' is not assignable to type 'MouseEvent<Element, MouseEvent>'.
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(event: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.ts(2769)

努力

  • 鼠标事件
  • 鼠标事件元素,鼠标事件〉
  • 鼠标事件

不幸的是,我发现什么都帮不上忙。

6ojccjat

6ojccjat1#

在父div上,添加onClick属性:

<div onClick={handleClickOutside}>
  {/* Other elements here */}
</div>

然后将handleClickOutside函数移出useEffect块。

相关问题