仅当我单击背景或关闭图标时,React Modal才会关闭吗?

时间:2020-10-19 05:09:19

标签: reactjs

这是一个Codepen https://codesandbox.io/s/amazing-morning-ukxp2?file=/src/App.js

因此,我创建了这个模态,并用一个Background样式的组件包装了它,但是我不知道如何仅在单击背景或关闭图标的情况下才能使close函数起作用。 / p>

现在,我的整个模态都用这个background包裹起来,所以无论我在哪里单击它总是关闭。我只希望在单击BackgroundCloseModalButton时关闭它,而不是在单击实际模态时关闭它。

这是我的下面的代码

      export const Modal = ({ showModal, setShowModal }) => {
        const animation = useSpring({
          opacity: showModal ? 1 : 0,
          transform: showModal ? `translateY(0%)` : `translateY(-200%)`
        });

        return (
          <>
            {showModal ? (
              <Background onClick={() => setShowModal(!showModal)}>
                <animated.div style={animation}>
                  <ModalWrapper showModal={showModal}>
                    <div>hi</div>
                    <CloseModalButton
                      aria-label='Close modal'
                      onClick={() => setShowModal(!showModal)}
                    />
                  </ModalWrapper>
                </animated.div>
              </Background>
            ) : null}
          </>
        );
      };

这是我的App.js,具有打开和关闭模式的功能

    function App() {
      const [showModal, setShowModal] = useState(false);

      const openModal = () => {
        setShowModal(!showModal);
      };

      return (
        <Container>
          <Button onClick={openModal}>Aye what's good</Button>
          <Modal showModal={showModal} setShowModal={setShowModal} />
          <GlobalStyle />
        </Container>
      );
    }

主要问题是背景包裹了我的整个模态,所以我需要一种方法来仅在目标是实际背景或X图标而不是实际模态本身时触发我的关闭函数(包裹在背景)

2 个答案:

答案 0 :(得分:0)

您需要跟踪event.target,其中给出了被称为的地方,即

const closeModal = (event) => {
    const modal = document.getElementById("myModal");
    if (event.target === modal) {
      setShowModal(false);
    }
  };
<Background id="myModal" onClick={closeModal}>

以下是演示:https://codesandbox.io/s/cranky-hodgkin-o77em?file=/src/components/Modal.js

答案 1 :(得分:0)

问题是由于事件冒泡。每次单击Background元素的任何后代时,它们的单击处理程序都会触发并起泡,直到到达Background元素,从而触发其自身的处理程序。要解决此问题,您可以使用stopPropagation()方法停止传播子元素的点击处理程序,也可以将 ID 添加到背景中并确定ID是否仅与背景匹配,然后触发showModal方法。

<Background onClick={closeModal} id="bg">

const closeModal = (e) => {
    if (e.target.id === 'bg') {
      setShowModal(false);
    }
  };

不必在关闭按钮上添加id并检查目标按钮的id,因为单击按钮肯定会关闭模式。

相关问题