简体   繁体   English

React 使用自定义钩子检测组件外的点击

[英]React detect click outside a component with custom hook

I'm trying to create a custom hook as I read in other StackOverflow responses, to detect a click outside the component.当我在其他 StackOverflow 响应中阅读时,我正在尝试创建一个自定义钩子,以检测组件外的点击。 I'm not sure what I'm missing here but something is not working right.我不确定我在这里缺少什么,但有些东西不正常。 The event needs to be appended only to the checkbox dropdown menu so when the user is open the dropdown and clicking outside the menu it will automatically close itself.该事件只需要附加到复选框下拉菜单,这样当用户打开下拉菜单并在菜单外单击时,它会自动关闭。 Although it looks like it works, you can notice that although the dropdown closed when the user clicks outside, it also prevents you from checkbox the input.虽然它看起来有效,但您可以注意到,虽然下拉菜单在用户单击外部时关闭,但它也会阻止您勾选输入。

Check my code here: SandBox Any help will be greatly appreciated在此处检查我的代码: SandBox任何帮助将不胜感激

I think it was just a typo.我认为这只是一个错字。 in your sandbox i fixed the handleClickOutside like this:在您的沙箱中,我像这样修复了 handleClickOutside:

  const handleClickOutside = (event) => {
    console.log(event.target);
    if (ref.current && !ref.current.contains(event.target)) {
      setIsComponentVisible(false);
    }
  };

there was missing a "t" in the "target" in !ref.current.contains(event.target) !ref.current.contains(event.target) 中的“目标”中缺少“t”

Is it working for you now?它现在对你有用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM