在外部点击时是否关闭模式?

时间:2019-02-19 12:30:40

标签: javascript reactjs

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

enter image description here

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>

3 个答案:

答案 0 :(得分:1)

您也可以在模式内部的Button上添加引用,并检查目标元素是否包含在其中

    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>

答案 1 :(得分:1)

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

您应该将<Modal>包裹到不可见的<Wrapper>中,其z-index值比模态值要小,并采用以下样式,以使父元素/窗口的全宽和全高:< / p>

.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附加到<Wrapper>上,并在您的handleClick方法中,将!==替换为===(因为请记住,我们已解决了该问题)。

希望获得帮助。

答案 2 :(得分:0)

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

相关问题