【发布时间】:2020-10-13 23:03:09
【问题描述】:
我在组件中制作了一个模态,数据工作正常,它是动态的,非常完美。问题是,当我打开它时,似乎每当我点击模式内的任何地方时,它都会再次关闭它。
模态是使用 useState 钩子管理的。我认为问题在于我的 onClick 调用进一步向下。有什么建议吗?
const LeaveRequestsUnits = () => {
let [data, setData] = useState([]);
let [modalState, setModalState] = useState(false);
let modalOnOff = () => {
setModalState(!modalState);
};
let [selectedUnit, setSelectedUnit] = useState('');
let updateSelectedUnit = (item) => {
setSelectedUnit(item);
const getLeaveUnits = data.map((item) => {
// fct to update the modalState and display-block the modal
const openModal = (item) => {
updateSelectedUnit(item);
modalOnOff();
$('.modalBackground').css('display', 'block');
};
const modal = () => {
return (
<div>
<p>{selectedUnit.note}</p>
<p>{selectedUnit.start}</p>
<p>{selectedUnit.end}</p>
<a href="https://www.google.com">Google</a>
<h1>Close</h1>
</div>
);
};
// display:none the modal if the modalState is false
if (!modalState) {
$('.modalBackground').css('display', 'none');
}
if (item.end >= today && item.approved !== false) {
return (
<div
className={unitColour}
key={item.reqID}
onClick={() => openModal(item)}
>
<div className='unitLeft'>
<img src={statusIcon} alt='Status Icon' id='statusIcon' />
</div>
<div className='unitMiddle'>
<p id='unitLeaveType'>{leaveTypeName}</p>
<p id='unitDate'>{startEndDate(item.start, item.end)}</p>
</div>
<div className='unitDivider'></div>
<div className='unitRight'>
<p id='unitDuration'>
{convertTimestamp(item.duration, item.type)}
</p>
</div>
{/* modal */}
<div className={`modalBackground modalShowing-${modalState}`}>
{modal()}
</div>
{/* end modal */}
</div>
);
}
});
return <div className='requestsContainer
CSS 如下:
.modalBackground {
display: none;
z-index: 10000;
width: 80vw;
height: 250px;
background-color: white;
border-radius: 15px;
position: absolute;
top: 10vh;
overflow: hidden;
color: black;
opacity: 0;
pointer-events: none;
cursor: auto;
}
.modalShowing-true {
/* display: none;
position: absolute;
top: 0;
width: 100%;
height: 100%;
background-color: black;
opacity: 0.3; */
opacity: 1;
pointer-events: auto;
}
【问题讨论】:
-
在你调用
stopPropagation()的模态组件上放置一个点击监听器,也就是你的模态<div onClick={this.cancelClose}>的最顶部元素,该函数看起来像这样cancelClose(event) { event.stopPropagation() } -
其他说明。不要在这里使用 jquery 来更改类,jquery 和 react 都在尝试操作 DOM。最好让一个人为您处理,这样您要测试的东西就更少了。
-
@JohnRuddell 谢谢约翰。这就像一个魅力。烦人的是,我在最近的 React 课程中学到了这一点,但忘记了 stopPropagation!非常感谢您的帮助 - 我将不再懒惰,并接受您关于 jquery 与使用 DOM 做出反应的建议。我无法将您的评论标记为答案,但请随时这样做,我会这样做。再次感谢您。
标签: javascript reactjs modal-dialog