MUI中通过sx属性用三元运算符设置paddingLeft不生效问题
问题原因
你的sx属性没有生效,核心错误是把theme.spacing()调用用双引号包裹成了普通字符串,最终传给浏览器的CSS值是字面量theme.spacing(34),这不是合法的CSS长度属性值,浏览器会直接忽略这条无效样式,自然看不到效果。
正确的sx写法
MUI的sx属性支持传入回调函数获取当前主题实例,不需要把主题方法写成字符串,正确代码如下:
<Container maxWidth={false} className={classes.container} sx={{ paddingLeft: (theme) => open ? theme.spacing(34) : theme.spacing(200) }} >
如果你没有自定义修改过MUI主题的spacing换算规则(默认1单位对应8px),还可以用更简洁的数字简写,sx会自动把传入的数字按spacing规则换算成合法长度值:
<Container maxWidth={false} className={classes.container} sx={{ paddingLeft: open ? 34 : 200 }} >
注意:如果自定义主题修改过spacing换算比例,不要用简写写法,必须显式调用theme.spacing()保证计算结果正确。
style属性实现方案
完全可以用原生style属性实现这个动态样式需求,只需要先通过MUI提供的useTheme钩子拿到主题实例,直接取spacing计算结果传入即可:
import { useTheme } from '@mui/material/styles'; // 组件内部 const theme = useTheme(); return ( <Container maxWidth={false} className={classes.container} style={{ paddingLeft: open ? theme.spacing(34) : theme.spacing(200) }} > )
两种方案选型参考:如果样式只涉及动态数值切换,不需要用到响应式断点、主题色、伪类选择器等sx独有的能力,用style属性性能更好;如果需要联动主题的其他设计token,优先用sx写法,省去手动调用useTheme的步骤。
内容的提问来源于stack exchange,提问作者user19251203
相关产品推荐
相关产品推荐

