我的自定义模式不会因为React' usestate Hook而关闭
我的自定义模态窗口打开了,但是当我单击黑暗的区域时,我没有关闭。我进行了一些调查,发现模态组件中的固定功能由于某种原因没有将Active to Active设置为False。我该如何解决?
模态文件
import React from 'react'
import './style.css'
const Modal = ({active, setActive, children}) => {
return (
<div className={active?'modal_main active':'modal_main'} onClick={()=>{setActive(false)}}>
<div className={active?'modal_content active':'modal_content'} onClick={e=>e.stopPropagation()}>
{children}
</div>
</div>
)
}
export default Modal
我使用模式窗口模式
import React, { useState } from 'react'
import Modal from '../../modal'
import './style.css'
function TagItem(props) {
const [tagActive, setTagActive] = useState(false);
return (
<div className='tag-item' onClick={()=>setTagActive(true)}>
{props.tag}
<Modal active = {tagActive} setActive = {setTagActive}>
<div >{props.tag}</div>
</Modal>
</div>
)
}
export default TagItem
的CSS
.modal_main{
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.4);
position: fixed;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
pointer-events: none;
transition: 0.5s;
z-index:1;
}
.modal_main.active{
opacity: 1;
pointer-events: all;
}
.modal_content{
padding: 20px;
border-radius: 12px;
background-color: white;
height: fit-content;
width: fit-content;
transform: scale(0.5);
transition: 0.4s all;
}
.modal_content.active{
transform: scale(1);
}
TAG-ITEM的CSS的
.tag-item{
border: 1px limegreen solid;
border-radius: 8px;
background-color: rgb(178, 246, 119);
width: fit-content;
padding: 2px;
margin: 2px;
cursor: default;
}
.tag-item:hover{
cursor: default;
background-color: rgb(1, 152, 1) ;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发出
在模式的外部
div
元素中 单击事件,正在触发状态更新,但是它也从
modal组件中传播到
tagitem <代码>组件的 div元素,这起了
tagactive状态更新为
true`。关闭模式的状态更新被覆盖。解决方案
停止外部
div
元素的单击事件的传播。Issue
The click event from the modals's outer
div
elementis triggering the state update, but it's also propagated out of the
Modalcomponent to the
TagItemcomponent's
divelement and this enqueues a
tagActivestate update to
true`. The state update to close the modal is overwritten.Solution
Stop the propagation of the outer
div
element's click event.