【发布时间】:2019-05-27 08:07:58
【问题描述】:
我一直在尝试在我的系统中实现 onclick 模式关闭。我已经使用关闭按钮实现了模态 onclick 事件,但在模态外部单击时没有成功
我已经尝试在 div 上添加 onclick 侦听器,但即使在模态窗口内单击,内容也会关闭。
<div
className={"Overlay " + (this.state.hidden? "hidden": "show")}
id={this.props.id + "-container"} onClick={() => {
this.setState({ hidden: true })
}}>
这是我目前的模态框渲染代码
render() {
const contentClassName = this.getContentClassName();
if (this.props.show) {
document.body.style.overflow = 'hidden';
}
const contentStyle = {
width: this.props.width,
height: this.props.height,
position: "relative"
};
return (
<div
className={"Overlay " + (this.state.hidden? "hidden": "show")}
id={this.props.id + "-container"} onClick={() => {
this.setState({ hidden: true })
}}>
<div className={contentClassName}>
<div className={"Overlay-container"} style={contentStyle}>
<a id={this.props.id + '-closeButton'}
className="Overlay-closeBtn icon-close-zoom" onClick={() => {
this.setState({ hidden: true })
}}/>
{this.props.children}
</div>
</div>
</div>
);
}
正如预期的那样,我希望在模式窗口外单击时关闭模式。目前,即使在单击模态窗口后它也会关闭。
【问题讨论】:
-
点击孩子(cointainer),使用
event.stopImmediatePropagation()。另请阅读event bubbling。 -
我会读这篇
-
所以基本上这里发生的是,当您在模态框内单击时,
onclick事件会冒泡到父 div,您隐藏模态框的位置。即父母的听众被解雇,因此行为。
标签: javascript preact