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

如何将MUI旧代码中的withStyles适配至MUI v5?

将MUI v4代码迁移至MUI v5实现相同布局功能

原MUI v4代码片段

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Hidden from '@material-ui/core/Hidden';
import Typography from '@material-ui/core/Typography';

const styles = theme => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: 'center',
    color: theme.palette.text.secondary
  }
});

const ColumnDirection = withStyles(styles)(({ classes }) => (
  <div className={classes.root}>
    <Grid container justify="space-around" spacing={4}>
      <Grid item xs={3}>
        <Grid container direction="column" spacing={2}>
          {/* 子组件内容 */}
        </Grid>
      </Grid>
    </Grid>
  </div>
));

MUI v5迁移实现要点

  • 包路径更新:所有@material-ui/core/*的导入替换为@mui/material/*
  • 样式方案替换:用MUI v5的styled API替代withStyles高阶组件(也可直接用sx属性快速实现内联样式)
  • Grid属性调整:v4的justify属性在v5中更名为justifyContent,对齐CSS原生属性命名规范

完整MUI v5实现代码

import React from 'react';
import { styled } from '@mui/material/styles';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Hidden from '@mui/material/Hidden';
import Typography from '@mui/material/Typography';

// 使用styled创建带样式的自定义组件
const StyledRoot = styled('div')(({ theme }) => ({
  flexGrow: 1,
}));

const StyledPaper = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(2),
  textAlign: 'center',
  color: theme.palette.text.secondary,
}));

const ColumnDirection = () => (
  <StyledRoot>
    <Grid container justifyContent="space-around" spacing={4}>
      <Grid item xs={3}>
        <Grid container direction="column" spacing={2}>
          {/* 可在此添加子组件,比如<StyledPaper>...</StyledPaper> */}
        </Grid>
      </Grid>
    </Grid>
  </StyledRoot>
);

export default ColumnDirection;

轻量化替代写法(用sx属性)

如果追求更简洁的代码,可以直接用sx属性省略styled组件定义:

const ColumnDirection = () => (
  <div sx={{ flexGrow: 1 }}>
    <Grid container justifyContent="space-around" spacing={4}>
      <Grid item xs={3}>
        <Grid container direction="column" spacing={2}>
          <Paper sx={{ padding: 2, textAlign: 'center', color: 'text.secondary' }}>
            {/* 组件内容 */}
          </Paper>
        </Grid>
      </Grid>
    </Grid>
  </div>
);

内容的提问来源于stack exchange,提问作者user9695260

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:00:54