开发者问题收集

未捕获的 TypeError:无法使用 React 和 useRef 读取未定义的属性

2022-08-15
630

因此,这是我在目标单击之外处理的函数,用于关闭某些模型和内容,但控制台上的错误消息显示如下错误消息:

Uncaught TypeError: Cannot read properties of undefined (reading 'contains')

我想知道如何处理 undefined ,以便该函数不会调用,或者至少从控制台隐藏。

这是我的处理方式:

 let useClickOutside = (handler) => {
        let domNode = useRef();

        useEffect(() => {
            let maybeHandler = (event) => !domNode.current.contains(event.target) && handler();
            document.addEventListener("mousedown", maybeHandler);
            return () => document.removeEventListener("mousedown", maybeHandler);
        });

        return domNode;
    };
1个回答

解决方案 1 :使用 可选链接 (?.)

let useClickOutside = (handler) => {
        let domNode = useRef();

        useEffect(() => {
            let maybeHandler = (event) => !domNode.current?.contains(event.target) && handler();
            document.addEventListener("mousedown", maybeHandler);
            return () => document.removeEventListener("mousedown", maybeHandler);
        });

        return domNode;
    };

解决方案 2 :使用 逻辑 AND (&&)

 let useClickOutside = (handler) => {
        let domNode = useRef();

        useEffect(() => {
            let maybeHandler = (event) =>  domNode.current && !domNode.current.contains(event.target) && handler();
            document.addEventListener("mousedown", maybeHandler);
            return () => document.removeEventListener("mousedown", maybeHandler);
        });

        return domNode;
    };
Sanket Shah
2022-08-15