【问题标题】:Hide Div onClick when clicking outside the child div | ReactJS在子 div 外部单击时隐藏 div onClick |反应JS
【发布时间】:2018-12-26 19:35:34
【问题描述】:

我目前在父 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 关闭。

谢谢!

【问题讨论】:

  • 请同时添加Javascript代码;像现在这样,人们很难提供帮助。
  • 您是否尝试将event.stopPropagation(); 应用于子div?

标签: javascript html css reactjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多