由于反应的 useState 钩子,我的自定义模式没有关闭

My custom modal doesn't close because of react's useState hook

我的自定义模式 window 打开但在我单击变暗区域时没有关闭。我调查了一下,发现模态组件中的 setActive 函数由于某种原因没有将 active 设置为 false。我该如何解决这个问题?

模态文件

import React from 'react'
import './style.css'


const Modal = ({active, setActive, children}) => {

  return (
    <div className={active?'modal_main active':'modal_main'} onClick={()=>{setActive(false)}}>
        <div className={active?'modal_content active':'modal_content'} onClick={e=>e.stopPropagation()}>
           {children}
        </div>
    </div>
  )
}

export default Modal

我在哪里使用模态window

import React, { useState } from 'react'
import Modal from '../../modal'
import './style.css'

function TagItem(props) {
  const [tagActive, setTagActive] = useState(false);

  return (
    <div className='tag-item' onClick={()=>setTagActive(true)}>
      {props.tag}
      <Modal active = {tagActive} setActive = {setTagActive}>
        <div >{props.tag}</div>
      </Modal>
    </div>
  )
}

export default TagItem

模态的css

.modal_main{
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.4);
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    pointer-events: none;
    transition: 0.5s;
    z-index:1;
}

.modal_main.active{
    opacity: 1;
    pointer-events: all;
}

.modal_content{
    padding: 20px;
    border-radius: 12px;
    background-color: white;
    height: fit-content;
    width: fit-content;
    transform: scale(0.5);
    transition: 0.4s all;
}

.modal_content.active{
    transform: scale(1);
}

标签项的 css

.tag-item{
    border: 1px limegreen solid;
    border-radius: 8px;
    background-color: rgb(178, 246, 119);
    width: fit-content;
    padding: 2px;
    margin: 2px;
    cursor: default;
}

.tag-item:hover{
    cursor: default;
    background-color: rgb(1, 152, 1) ;
}

问题

来自模态框外div元素的点击事件is triggering the state update, but it's also propagated out of theModalcomponent to theTagItemcomponent'sdivelement and this enqueues atagActivestate update to是的`。关闭模态的状态更新被覆盖。

解决方案

停止传播外部 div 元素的点击事件。

const Modal = ({ active, setActive, children }) => {
  return (
    <div
      className={active ? "modal_main active" : "modal_main"}
      onClick={(e) => {
        e.stopPropagation(); // <-- stop propagation to parent component
        setActive(false);
      }}
    >
      <div
        className={active ? "modal_content active" : "modal_content"}
        onClick={(e) => {
          e.stopPropagation();
        }}
      >
        {children}
      </div>
    </div>
  );
};