首页 > 解决方案 > 在子 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 关闭。

谢谢!

标签: javascripthtmlcssreactjs

解决方案


为子 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>
    );
  }
)

推荐阅读