简体   繁体   English

React 模态提前关闭

[英]React Modal Closing Early

I created a modal in React that is currently opening.我在 React 中创建了一个当前打开的模态。 However, no matter where I click, be it the close button, the modal body, or the background overlay, the modal closes.但是,无论我点击哪里,无论是关闭按钮、模态主体还是背景叠加层,模态都会关闭。

I initially was not passing the Synthetic event into my handler.我最初没有将 Synthetic 事件传递到我的处理程序中。 I have since passed in the object and tried adding stopPropagation() , nativeEvent.stopPropagation() , and nativeEvent.stopImmediatePropagation() to no avail.我已通过 object 并尝试添加stopPropagation()nativeEvent.stopPropagation()nativeEvent.stopImmediatePropagation()无济于事。 The code is below, let me know what I messed up.代码在下面,让我知道我搞砸了什么。

I am using styled-components for this project, so the wrapping JSX tags belong to styled components which I ommitted.我在这个项目中使用了样式组件,所以包装 JSX 标签属于我省略的样式组件。

  • Thanks.谢谢。

Parent Component父组件

interface ParentProps {
    title: string;
    img: string;
    modalContent: JSX.Element;
}

function Parent(props: ParentProps) {

    const [modalize, setModalize] = useState(false);

    function toggleModal(event: SyntheticEvent) {
        setModalize(!modalize);
        event.stopPropagation();
        event.nativeEvent.stopPropagation();
    }

    return (
        <SkillBoxWrapper
            img={process.env.PUBLIC_URL + "/" + props.img}
            onClick={(e) => toggleModal(e)}
        >
            <BoxTitle className="title">{props.title}</BoxTitle>
            <Modal show={modalize} toggleModal={() => toggleModal}>{props.modalContent}</Modal>
        </SkillBoxWrapper>
    );
}

Modal Component模态组件

interface ModalProps {
    children: JSX.Element;
    toggleModal: (e: SyntheticEvent) => void;
    show: boolean;
}

function Modal(props: ModalProps) {
    return props.show
        ? (
            <ModalBackground>
                <ModalDisplayArea>
                    <button onClick={(e) => props.toggleModal(e)}>X</button>
                    <div className="modal-content">{props.children}</div>
                </ModalDisplayArea>
            </ModalBackground >
        )
        : null;
}

Your modal is within SkillBoxWrapper, which still listens to onClick when modal is shown and therefore toggles modal.您的模态框位于 SkillBoxWrapper 内,它在显示模态框时仍会监听 onClick,因此会切换模态框。 You may only care for opening modal from SkillBoxWrapper, which solves the issue.您可能只关心从 SkillBoxWrapper 打开模式,这解决了这个问题。

return (
        <SkillBoxWrapper
            img={process.env.PUBLIC_URL + "/" + props.img}
            onClick={(e) => { if(!modalize) toggleModal(e) } }
        >
            <BoxTitle className="title">{props.title}</BoxTitle>
            <Modal show={modalize} toggleModal={() => toggleModal()}>{props.modalContent}</Modal>
        </SkillBoxWrapper>
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM