我正在尝试检测一组组件之外的点击。我有多个名为
Block
的组件,位于 Artboard
组件内。在每个 Block
组件中,这就是我现在所拥有的:
const handleClickOutside = (e) => {
if (ref && !ref.contains(e.target)) {
setSelected(false);
}
}
所以这是可行的,但是每当我想实际单击一个块并选择它时,
handleClickOutside()
实际上会触发,因为我在每个其他块组件之外单击。
-------
| |
| |
| |
-------
^ This is a selected block
When I click outside of it, it will be deselected.
-------
| |
| |
| |
-------
^ But when I click on this block, I'm also clicking
outside the beforementioned block, which causes the
handleClickOutside function to fire.
我只是希望能够选择一个组件,然后通过单击其外部来取消选择它,而不影响其他块组件。
我不确定这是否是正确的方法,但我已经在 Codesandbox 上尝试过。它适用于您定义的用例。
因此,在
onClick
组件的 Box
处理程序中,您调用 preventDefault
,并在处理程序 handleClickOutside
中检查 e.defaultPrevented
是否为 true
。
这里是Codesandbox链接:https://codesandbox.io/s/headless-wind-tr1ns
此外,如果您可以使用
ref
作为 Box
组件。您可以阅读这个答案:How to open and close dropdown on btn-click,但同时与外部单击关闭?
希望这有帮助!
也在寻找更好的答案。谢谢:)