javascript - 如何在模态之外使用 handleClick 关闭模态?
问题描述
实际上,我isAvatarUserMenuOpen
在课堂上使用了道具UserDataPresentation
,以了解模态是否打开。我使用此状态生成影响 onClick 打开和关闭模态的条件。但是我需要通过在此模式之外进行的任何点击来关闭此模式,实际上它只在打开它的同一个按钮中关闭。
我一直在做一个handleClick,它在打开模式时添加一个监听器,当我在模式外单击时,它会显示一个警报“关闭模式!”。我需要删除此警报,并找到关闭模式的方法,就像打开和关闭模式的 onclick 一样。
export class UserDataPresentation extends React.Component<Props> {
node: any
componentWillMount() {
document.addEventListener('mousedown', this.handleClick, false)
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClick, false)
}
handleClick = (e: { target: any }) => {
if (!this.node.contains(e.target)) {
alert('close de modal!')
return
}
}
render() {
const { openMenuUserModal, closeMenuUserModal, isAvatarUserMenuOpen } = this.props
return (
<React.Fragment>
<div className="user-data-container" ref={isAvatarUserMenuOpen ? (node) => (this.node = node) : null}>
<div className="text">
<p>Wolfgang Amadeus</p>
</div>
<div className="avatar">
<img src={avatarPhoto} />
</div>
<a href="#" onClick={isAvatarUserMenuOpen ? closeMenuUserModal : openMenuUserModal}>
<div className="svg2">
<SVG src={downArrow} cacheGetRequests={true} />
</div>
</a>
</div>
</React.Fragment>
)
}
}
解决方案
我经常遇到这个问题并且总是做以下事情。
我混合 css 定位和反应钩子来创建一个模态。覆盖层 div 覆盖了整个 div 容器,因此当您单击容器中除模态之外的任何位置时,模态消失。#modal 上的 z-index:1 确保模态堆叠在覆盖层之上。
const Modal = () => {
const [modal, setModal] = React.useState(false);
return (
<div id='container'>
<button onClick={() => setModal(true)}>toggle modal</button>
{modal && <div id='overlayer' onClick={() => setModal(false)}></div>}
{modal && <div id='modal'>modal</div>}
</div>
);
};
ReactDOM.render(<Modal/>, document.getElementById("react"));
#container{
position: relative;
height: 200px; width:200px;
border: 1px solid black;
}
#container * {position: absolute;}
#overlayer{
height: 100%; width:100%;
}
#modal{
background: blue;
height: 30%; width:30%;
top: 12%; z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
推荐阅读
- c - 在结构中设置数组数据
- statsmodels - PyMC3 中的 SARIMAX 模型
- c++ - C++ 的 VisibleForTesting 注释
- r - pcalg 包上的 `pdag2allDags` 和 `addBgKnowledge` 函数存在问题
- c++ - 写一个程序写3个成绩,然后计算平均值,以及显示用户输入的字母成绩
- gradle - 使用预定义的 POM 发布 jar 工件
- javascript - 使用 API 值作为道具来改变 React 中的状态
- flutter - Flutter 会自动调整元素(图标、图像等)的大小以适应屏幕尺寸吗?
- imagemagick - 使用 imagemagick 将 EPS(EPT) 转换为 PNG/GIF 会创建额外的帧
- arrays - 我如何(继续,post-Kotlin Android Extensions)将小部件作为数组元素(双重包含)访问?