React ModalUnstyled点击外部无法关闭问题求助
解决React ModalUnstyled点击外部无法关闭的问题
问题现象
此前代码运行正常,如今点击React ModalUnstyled组件外部时,模态框无法关闭;但按下ESC键或直接调用handleUpdateClose()函数时,模态框可正常关闭。
问题原因
自定义的Backdrop组件设置了z-index: -1,这会让遮罩层处于模态框内容的下方,导致点击事件无法被遮罩层捕获,因此触发不了关闭逻辑。
解决方案
调整Backdrop的z-index值,确保它在模态框内容的下方但可被点击到,修改后的代码如下:
const Backdrop = styled('div')` z-index: 1299; /* 设置为比模态框z-index小的正数 */ position: fixed; right: 0; bottom: 0; top: 0; left: 0; background-color: rgba(0, 0, 0, 0.5); -webkit-tap-highlight-color: transparent; cursor: pointer; /* 可选,添加点击光标提示 */ `;
原理说明
ModalUnstyled的外部点击关闭逻辑依赖Backdrop组件的点击事件,当Backdrop的z-index为负数时,它会被模态框容器(StyledModal,z-index:1300)覆盖,点击外部区域实际上无法触发Backdrop的点击事件。将z-index改为1299(小于模态框的z-index),既保证遮罩层在模态框内容后方,又能被点击到,此时点击外部遮罩层就能正常触发onClose回调。
内容的提问来源于stack exchange,提问作者Kyle Andrew
相关产品推荐
相关产品推荐

