Material UI Modal被背景遮罩变暗,显示异常求助
解决Material UI Modal内容被背景遮罩变暗的问题
问题现象
使用Material UI Modal展示交易处理状态时,背景遮罩的变暗效果同时作用在了Modal内容本身,本该显示为白色的Modal呈现出深灰色。

问题原因
你直接将样式通过sx属性传给了Modal组件本身,但Material UI的Modal组件的sx样式是作用在包含背景遮罩的根容器上的,这会导致内容区域和遮罩层的样式产生冲突,最终让内容被遮罩的变暗效果覆盖。
解决方案
将原本的modalStyle应用到Modal内部的内容容器上,而非直接传给Modal组件:
样式代码(无需修改)
const modalStyle = { position: 'absolute' as 'absolute', top: 0, left: 0, width: "80%", marginLeft: "auto", marginRight: "auto", marginTop: "150px", marginBottom: "150px", bgcolor: 'white', boxShadow: 24, p: 3, borderRadius: "25px" }
修改后的组件代码
<Modal open={open} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > {/* 将样式转移到内部的Box容器上 */} <Box sx={modalStyle}> {!done ? ( <div style={{ display: "flex", flexDirection: "column", height: "100%", alignItems: "center" }}> <h1 style={{ fontSize: "50px", textAlign: "center", fontWeight: "700" }}>Transaction Loading...</h1> <Box style={{ display: 'flex', width: "300px", height: "300px", justifyContent: "center" }}> <CircularProgress style={{ marginTop: "50px" }} size={150} /> </Box> </div>) : ( <div style={{ display: "flex", flexDirection: "column", height: "100%", alignItems: "center" }}> <h1 style={{ fontSize: "50px", textAlign: "center", fontWeight: "700" }}>Transaction Completed!</h1> <svg className={styles.animatedCheck} viewBox="0 0 24 24"> <path d="M4.1 12.7L9 17.6 20.3 6.3" fill="none" /> </svg> </div>)} </Box> </Modal>
原理说明
Material UI的Modal组件内部会自动生成独立的背景遮罩层和内容容器层,只有将样式作用在内容容器上,才能确保内容层被正确渲染在遮罩层之上,避免被遮罩的变暗效果影响。
内容的提问来源于stack exchange,提问作者Silas Lenihan
相关产品推荐
相关产品推荐

