【发布时间】:2020-10-19 05:09:19
【问题描述】:
这是一个代码笔https://codesandbox.io/s/amazing-morning-ukxp2?file=/src/App.js
所以我创建了这个模态,并用Background 样式的组件包装了它,但我不知道如何让关闭功能仅在我只单击背景或关闭图标时才起作用。
现在我的整个模式都被这个background 包裹着,所以无论我在哪里点击它总是会关闭。我只希望它在我点击Background 或CloseModalButton 时关闭,而不是在我点击我的实际模式时关闭。
下面是我的代码
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 图标而不是实际模态本身(包裹在背景)
【问题讨论】:
-
你能重现codesandbox中的输出吗?
-
这与您的问题无关,但是在切换模式时,您应该使用
setShowModal的先前状态,例如:setShowModal(prev => !prev)。 -
@Scratch'N'Purr prev 和将状态切换到与 !showModal 值相反的状态有什么区别?
-
@JuliusGuevarra 我在上面添加了代码框的链接
标签: reactjs