You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:36:01