【发布时间】:2021-02-02 12:24:59
【问题描述】:
所以我有这个被整个背景 div 包裹的模态。我的问题是我在后台添加了一个关闭功能,所以无论我点击哪里,它都会关闭模态。
我想让 useRef 只针对背景 div,如果我点击其中的任何子元素,它就不起作用
这里是代码
const modalRef = useRef();
const closeModal = e => {
if (modalRef.current.contains(e.target)) {
setShowModal(false);
}
}
return (
<>
{showModal ? (
<Background onClick={closeModal} ref={modalRef}>
<animated.div style={animation}>
<ModalWrapper showModal={showModal}>
<div>hi</div>
<CloseModalButton
aria-label='Close modal'
// onClick={() => setShowModal(!showModal)}
/>
</ModalWrapper>
</animated.div>
</Background>
) : null}
</>
);
};
所以现在 ref 已附加到背景,但如果我 console.log(modalRef.current) 它会向我显示整个 jsx,其中包含我所有的子 div,但我只想定位外部 div 也就是背景
所以每当我在我的模态之外点击它都会关闭
注意:当我使用 console.log(modalRef.current) 时,这就是控制台中显示的内容,也就是我的整个 JSX
我也在使用 styled-components,所以我只想定位我称为 Background 但显示 sc-bdnylx iEsAwc 的顶部 div,所以我不知道如何定位它,因为它没有任何 id 或类名
我试图添加这个 console.log(modalRef.current.children[0]),但是当我将它实现到我的函数中时,它不能正常工作。这个console.log 确实只显示了我的Background div 下面的div,但我还没有发现任何关于只针对Background 的信息
【问题讨论】:
-
您是否尝试过将目标与参考进行比较?例如
if (modalRef.current === e.target) { -
啊,谢谢!