首页 > 解决方案 > 如何在模态之外使用 handleClick 关闭模态?

问题描述

实际上,我isAvatarUserMenuOpen在课堂上使用了道具UserDataPresentation,以了解模态是否打开。我使用此状态生成影响 onClick 打开和关闭模态的条件。但是我需要通过在此模式之外进行的任何点击来关闭此模式,实际上它只在打开它的同一个按钮中关闭。

我一直在做一个handleClick,它在打开模式时添加一个监听器,当我在模式外单击时,它会显示一个警报“关闭模式!”。我需要删除此警报,并找到关闭模式的方法,就像打开和关闭模式的 onclick 一样。

export class UserDataPresentation extends React.Component<Props> {
  node: any
  componentWillMount() {
    document.addEventListener('mousedown', this.handleClick, false)
  }

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

  handleClick = (e: { target: any }) => {
    if (!this.node.contains(e.target)) {
      alert('close de modal!')
      return
    }
  }

  render() {
    const { openMenuUserModal, closeMenuUserModal, isAvatarUserMenuOpen } = this.props
    return (
      <React.Fragment>
        <div className="user-data-container" ref={isAvatarUserMenuOpen ? (node) => (this.node = node) : null}>
          <div className="text">
            <p>Wolfgang Amadeus</p>
          </div>
          <div className="avatar">
            <img src={avatarPhoto} />
          </div>
          <a href="#" onClick={isAvatarUserMenuOpen ? closeMenuUserModal : openMenuUserModal}>
            <div className="svg2">
              <SVG src={downArrow} cacheGetRequests={true} />
            </div>
          </a>
        </div>
      </React.Fragment>
    )
  }
}

标签: javascriptreactjsecmascript-6react-redux

解决方案


我经常遇到这个问题并且总是做以下事情。

我混合 css 定位和反应钩子来创建一个模态。覆盖层 div 覆盖了整个 div 容器,因此当您单击容器中除模态之外的任何位置时,模态消失。#modal 上的 z-index:1 确保模态堆叠在覆盖层之上。

const Modal = () => {
  const [modal, setModal] = React.useState(false);
  return (
    <div id='container'>
      <button onClick={() => setModal(true)}>toggle modal</button>
      {modal && <div id='overlayer' onClick={() => setModal(false)}></div>}
      {modal && <div id='modal'>modal</div>}
      
    </div>
  );
};

ReactDOM.render(<Modal/>, document.getElementById("react"));
#container{ 
  position: relative;
  height: 200px; width:200px;
  border: 1px solid black;
 }
#container * {position: absolute;}

#overlayer{ 
  height: 100%; width:100%;
 }
#modal{ 
background: blue;
 height: 30%; width:30%;
 top: 12%; z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>


推荐阅读