javascript - 在子 div 外部单击时隐藏 div onClick | 反应JS
问题描述
我目前在父 div 中间有一个父 div 和一个子 div。我希望能够仅在单击子 div 外部时关闭父 div。我该怎么做呢?我的代码当前设置如下,使用 triggerParentUpdate 设置 true 或 false 是否显示 div。
<div onClick={this.props.triggerParentUpdate} className="signupModalContainer">
<div className="embed-responsive embed-responsive-16by9">
<form action="action_page.php">
<div className="container">
<button onClick={this.props.triggerParentUpdate} type="button" className="closebtn">X</button>
</div>
</form>
</div>
</div>
第一个 div (className="signupModalContainer") 中的 onclick 函数使得当我单击该 div 或任何子 div 时,所有 div 都会关闭。如果我把那个 onclick 函数去掉,那么 div 会通过 closebtn 关闭。
谢谢!
解决方案
为子 div 的事件处理程序创建一个处理onClick
程序,该处理程序停止将事件传播/冒泡到父项。
有关详细信息,请参阅Event.stopPropagation方法。
class SomeComponent extends Component {
handleCloseButton = e => {
// This stops the event from bubbling up.
// So it won't trigger the parent div's "onClick" to fire.
e.stopPropagation();
this.props.triggerParentUpdate(e);
}
render () {
// ...
return (
<div onClick={this.props.triggerParentUpdate} className="signupModalContainer">
<div className="embed-responsive embed-responsive-16by9">
<form action="action_page.php">
<div className="container">
<button onClick={this.handleCloseButton} type="button" className="closebtn">X</button>
</div>
</form>
</div>
</div>
);
}
)
推荐阅读
- arcore - ARCore - 增强图像增加跟踪的稳定性
- typescript - 带有声明元组的 Typescript lint “no-unused-vars”
- angular - 刷新页面后如何获取路由参数?
- git - 有什么方法可以在 github 中创建内部拉取请求?
- c# - 如何验证和删除 JSON 对象的嵌套节点
- gradle - 面临gradle的问题。Android Studio 也关闭了 Build bundle/apk
- git - 删除组开发人员的写权限
- javascript - 在输入字段上触发“点击”
- java - spring boot / jpa / maven / eclipse:元模型类不在项目中生成
- css - 带有 glsl 着色器的画布在某些 css 变换比例下中断