简体   繁体   English

条件在我的 function 关闭模态框时不起作用

[英]Condition doesn't work in my function closing a modal box

In my reactjs app there are the component 'Modal'.在我的 reactjs 应用程序中有组件“模态”。 It's an absolutely positionned block with x-index: 1000. One button in the component 'Menu' opens this modal in the main page.这是一个绝对定位的块,x-index:1000。组件“菜单”中的一个按钮在主页中打开此模式。 There is a function closing the modal box by clicking only outside the box.有一个 function 通过仅在框外单击来关闭模态框。 But modal closes by both outside and inside clicks - any conditions about clicking on the modal doesn't work and the box closes.但是模态通过外部和内部点击关闭 - 关于点击模态的任何条件都不起作用并且框关闭。 Why doesn't work conditions like 'id' or 'z-index' of the modal box?为什么模态框的“id”或“z-index”等条件不起作用?

const clickOutModal= (event) => { 
     if(event.target.id !== 'mymodal') {    //condition when modal box mustn't close
     clickModalClose();                     // working function based on useState for closing the modal box
      }             
  };

document.body.addEventListener('click', clickOutModal);

The second variant of condition I tried was我尝试的第二种情况是

if(event.target.zIndex !== '1000')

you want to have a background div that covers the entire screen with a z-index of maybe 1, that has a click event to close the modal.你想要一个覆盖整个屏幕的背景 div,z-index 可能为 1,它有一个点击事件来关闭模式。

Then your modal sits over top of that div and has a z-index of something higher (1000).然后您的模态位于该 div 的顶部,并且 z-index 更高(1000)。

I think it would be good to separate the components.我认为将组件分开会很好。 Have a modal and backdrop component.有一个模态和背景组件。

Also, React has their own click events: onClick.此外,React 有自己的点击事件:onClick。 You can read more about it here https://reactjs.org/docs/handling-events.html你可以在这里阅读更多关于它的信息https://reactjs.org/docs/handling-events.html

So, within the Modal component, you can have something like this:所以,在 Modal 组件中,你可以有这样的东西:

<React.Fragment>
   <Backdrop showModal={*T or F*} clicked={*Pass in function that handles click event*}/>
   <div>
      ...contents of modal
   </div>
</React.Fragment>

The Backdrop component represents the background. Backdrop 组件代表背景。 You can set the onClick event in that component and when it is clicked, it will fire the click event which you set on it.您可以在该组件中设置 onClick 事件,当单击它时,它将触发您在其上设置的单击事件。

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

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