如何在MUI V5中正确使用styled()实现旧版makeStyles的等效效果
错误点梳理
- 自定义styled组件首字母未大写,React会将其判定为原生HTML标签,样式无法正常注入
- DOM结构与旧版实现不匹配:旧版root样式直接绑定在Paper组件上,你的实现额外嵌套了一层div承载root样式,Paper被放在内层,结构逻辑完全错乱
- pageIcon样式原直接作用于Card组件,你的实现额外嵌套了一层div承载icon样式,Card无法继承到对应样式属性
theme.spacing调用未传入数值参数,返回值为函数而非实际像素值,边距样式失效
正确迁移代码
import { styled } from '@mui/material/styles'; import Paper from '@mui/material/Paper'; import Card from '@mui/material/Card'; import Typography from '@mui/material/Typography'; const RootPaper = styled(Paper)(({ theme }) => ({ backgroundColor: "#fdfdff", })); const PageHeaderWrapper = styled('div')(({ theme }) => ({ padding: theme.spacing(4), display: "flex", marginBottom: theme.spacing(2), // 可根据旧版实际效果调整spacing参数值 })); const IconCard = styled(Card)(({ theme }) => ({ display: "inline-block", padding: theme.spacing(2), color: "#3c44b1", })); const TitleWrapper = styled('div')(({ theme }) => ({ paddingLeft: theme.spacing(4), "& .MuiTypography-subtitle2": { opacity: "0.6", }, })); export default function PageHeader(props) { const { title, subTitle, icon } = props; return ( <RootPaper elevation={0} square> <PageHeaderWrapper> <IconCard>{icon}</IconCard> <TitleWrapper> <Typography variant="h6" component="div"> {title} </Typography> <Typography variant="subtitle2" component="div"> {subTitle} </Typography> </TitleWrapper> </PageHeaderWrapper> </RootPaper> ); }
内容的提问来源于stack exchange,提问作者Moe
相关产品推荐
相关产品推荐

