我正在寻找一种方法来检测单击事件是否发生在组件之外,如本文所述。jQueryclosest()用于查看单击事件的目标是否将dom元素作为其父元素之一。如果存在匹配项,则单击事件属于其中一个子项,因此不被视为在组件之外。
因此,在我的组件中,我想将一个单击处理程序附加到窗口。当处理程序启动时,我需要将目标与组件的dom子级进行比较。
click事件包含类似“path”的财产,它似乎保存了事件经过的dom路径。我不知道该比较什么,或者如何最好地遍历它,我想肯定有人已经把它放在了一个聪明的效用函数中。。。不
import React, { useState, useEffect, useRef } from "react";
const YourComponent: React.FC<ComponentProps> = (props) => {
const ref = useRef<HTMLDivElement | null>(null);
const [myState, setMyState] = useState(false);
useEffect(() => {
const listener = (event: MouseEvent) => {
// we have to add some logic to decide whether or not a click event is inside of this editor
// if user clicks on inside the div we dont want to setState
// we add ref to div to figure out whether or not a user is clicking inside this div to determine whether or not event.target is inside the div
if (
ref.current &&
event.target &&
// contains is expect other: Node | null
ref.current.contains(event.target as Node)
) {
return;
}
// if we are outside
setMyState(false);
};
// anytime user clics anywhere on the dom, that click event will bubble up into our body element
// without { capture: true } it might not work
document.addEventListener("click", listener, { capture: true });
return () => {
document.removeEventListener("click", listener, { capture: true });
};
}, []);
return (
<div ref={ref}>
....
</div>
);
};