Material UI v4迁移至v5的自定义样式问题:sx与styled用法求助
Material UI v5 迁移问题解答
一、修复sx属性的主题相关错误
你写的sx代码语法有误,sx属性中要访问主题变量时,有两种正确写法:
写法1:函数式取值
将样式值设为接收theme参数的函数,直接获取主题色值:
<Typography sx={{ color: (theme) => theme.palette.grey[300] }} variant="caption" > {props.person.location} </Typography>
写法2:主题路径简写
MUI的sx属性支持直接用字符串简写主题颜色路径,更简洁:
<Typography sx={{ color: 'grey.300' }} variant="caption" > {props.person.location} </Typography>
错误原因:你之前的写法{{theme.palette.grey[300]}}相当于给sx传了一个键名为theme.palette.grey[300]、值为undefined的对象,完全不符合sx的语法规则。
二、使用styled()自定义Material UI组件样式
完全可以用styled()来包装Box、AppBar等MUI组件,不需要局限于HTML元素,直接传入组件本身即可:
示例1:自定义Box样式
import { styled, Box } from '@mui/material'; const StyledBox = styled(Box)(({ theme }) => ({ padding: theme.spacing(2), backgroundColor: theme.palette.secondary.light, borderRadius: theme.shape.borderRadius, })); // 使用时直接调用StyledBox <StyledBox> {/* 内容 */} </StyledBox>
示例2:自定义AppBar样式
import { styled, AppBar } from '@mui/material'; const StyledAppBar = styled(AppBar)(({ theme }) => ({ backgroundColor: theme.palette.primary.dark, boxShadow: theme.shadows[4], })); // 使用方式 <StyledAppBar position="static"> {/* 导航内容 */} </StyledAppBar>
本质上,styled()既支持传入HTML标签名(如'div'),也支持传入MUI的组件实例,最终都会生成一个带自定义样式的新组件。
内容的提问来源于stack exchange,提问作者GLP
相关产品推荐
相关产品推荐

