【问题标题】:close modal when click outside?单击外部时关闭模式?
【发布时间】:2019-07-12 23:12:09
【问题描述】:

我有一个模态框,里面有几个按钮。在外部单击时,我希望该模式关闭。我已将 ref 添加到父元素,它工作正常,当您单击外部时,一切都会关闭。但是,如果您单击此模式框内的按钮,它也会关闭。如何检测此 ref 内的子元素并且不允许关闭模式框?

public handleClickoutside() {
this.props.showMessage()
}

public handleClick = (e) => {
if (this.DOMArrowBox.current !== e.target) {
  this.handleClickoutside()
}
}

public componentWillMount() {
document.addEventListener("mousedown", this.handleClick, false)
}

public componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClick, false)
}

<div className={this.props.className} ref={this.DOMArrowBox}>
    <Social />
    <CallMe className="arrow__box-button" open={this.props.open} />
    <Close
      className="arrow-button_close"
      onClick={this.props.showMessage}
    />
  </div>

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您也可以在模态框内的 Button 上添加 ref 并检查目标元素是否包含在其中

    public handleClickoutside() {
       this.props.showMessage()
    }

    public handleClick = (e) => {

        if (!this.DOMArrowBox.current.contains(e.target) && !ReactDOM.findDOMNode(this.btnRef.current).contains(e.target)) {
          this.handleClickoutside()
        }

    }

    public componentWillMount() {
        document.addEventListener("mousedown", this.handleClick, false)
    }

    public componentWillUnmount() {
        document.removeEventListener("mousedown", this.handleClick, false)
    }

    <div className={this.props.className} ref={this.DOMArrowBox}>
        <Social />
        <CallMe className="arrow__box-button" ref={this.btnRef}open={this.props.open} />
        <Close
          className="arrow-button_close"
          onClick={this.props.showMessage}
        />
     </div>

【讨论】:

    【解决方案2】:

    我认为解决此问题的最佳方法是还原问题: 让我们假设您没有捕捉到模态外部的点击,而是在模态背景包装器上的点击

    您应该将&lt;Modal&gt; 包装成一个不可见的&lt;Wrapper&gt;,其 z-index 小于模态,并使用以下样式,以获取父元素/窗口的全宽和高度:

    .modal-wrapper {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 1; // has to be < of Modal's z-index
        width: 100%; // or 100vw
        height: 100%; // or 100vh
    }
    

    然后,将ref 附加到&lt;Wrapper&gt; 上,并在您的handleClick 方法中,将!== 替换为===(因为请记住,我们恢复了问题)。

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      使用onBlur 事件处理clickoutside。请查看this answer 的工作示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        • 1970-01-01
        相关资源
        最近更新 更多