我正在尝试检测一组组件之外的点击。我在 Artboard
组件中有多个名为 Block
的组件。在每个 Block
组件中,这是我目前拥有的:
const handleClickOutside = (e) => {
if (ref && !ref.contains(e.target)) {
setSelected(false);
}
}
所以这行得通,但每当我想实际点击一个 block 并选择它时,handleClickOutside()
实际上会触发,因为我在所有其他 block 组件之外单击。
-------
| |
| |
| |
-------
^ 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.
我只是希望能够选择一个组件,然后通过在它的外部单击来取消选择它,而不影响其他 block 组件。
最佳答案
我不确定这是否是正确的方法,但我已经在 Codesandbox 上尝试过了。它适用于您定义的用例。
所以在 Box
组件的 onClick
处理程序中调用 preventDefault
并在处理程序 handleClickOutside
中检查是否e.defaultPrevented
为 true
。
这是 Codesandbox 链接:https://codesandbox.io/s/headless-wind-tr1ns
此外,如果您可以为 Box
组件使用 ref
。你可以阅读这个答案:How to open and close dropdown on btn-click, but in same time with outside click close?
希望这对您有所帮助!
也在寻找更好的答案。谢谢:)
关于javascript - react : Detect click outside multiple components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58626061/