简体   繁体   English

React-Bootstrap Modals 导致 window EventListener 出现问题

[英]React-Bootstrap Modals cause problems for window EventListener

I have built a React app which uses React-Bootstrap Modals.我已经构建了一个使用 React-Bootstrap Modals 的 React 应用程序。

In my return() function I have button which onClick changes state and shows/hides a div element.在我的 return() function 中,我有一个按钮,其中 onClick 更改为 state 并显示/隐藏一个 div 元素。

const [showInfo, setShowInfo] = useState(false);
 
const toggleInfo = React.useCallback(() => {
  setShowInfo(!showInfo);
}, [showInfo]);

useEffect(() => {
  if (showInfo) {
    document.addEventListener("click", toggleInfo);
    return () => {
      document.removeEventListener("click", toggleInfo);
    };
  }
}, [showInfo, toggleInfo]);

return (

...

<Button onClick={() => toggleInfo()}>

...
)

After loading the page, pressing the button changes the state and the div element is shown/hidden depending on the state. If I click anywhere on the window it hides the div element.加载页面后,按下按钮会更改 state 并根据 state 显示/隐藏 div 元素。如果我单击 window 上的任意位置,它会隐藏 div 元素。

Everything works fine until I open any Modal dialog.在我打开任何模态对话框之前,一切正常。

After that, when I click my button that shows/hides div the document.addEventListener("click", toggleInfo) and document.removeEventListener("click", toggleInfo) execute immediately one after the other and the div element does not get displayed.之后,当我单击显示/隐藏 div 的按钮时, document.addEventListener("click", toggleInfo)document.removeEventListener("click", toggleInfo)立即一个接一个地执行,div 元素不会显示。

If I reload the page, it works again and I made sure that this problem occurs only after opening the Modal dialog.如果我重新加载页面,它会再次运行,并且我确保只有在打开模态对话框后才会出现此问题。

Any help or tips would be greatly appreciated任何帮助或提示将不胜感激

Fixed the issue by adding e.stopPropagation() to the toggleInfo() function:通过将e.stopPropagation()添加到toggleInfo() function 解决了这个问题:

const toggleInfo = React.useCallback(
    (e) => {
      e.stopPropagation();
      setShowInfo(!showInfo);
    },
    [showInfo]
  );

return (

...

<Button onClick={(e) => toggleInfo(e)}>

...
)

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

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