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

Mui v5.0.4 makeStyles与withStyles无法为Mui组件正常应用样式问题

我目前基于 React v17 + Mui v5.0.4 开发项目,按需编写的自定义样式此前一直运行符合预期,时隔数天重启项目后,发现编写的样式未按预期渲染,该问题仅出现在 Typography、Button 等特定组件上。我已完整检查代码,切换不同浏览器和设备测试均未解决,新建项目测试也存在同样问题。
相关代码片段如下:

App.js

import React from 'react';

import Something from './something/Something';

function App() {
  return <Something />;
}

export default App;

Something.js

import React from 'react';
import PropTypes from 'prop-types';
import { Typography } from '@mui/material';
import { withStyles } from '@mui/styles';

import styles from './Something.styles';

const Something = ({ classes }) => {
  return <Typography className={classes.something}>Something</Typography>;
};

Something.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(Something);

Something.styles.js

const styles = (theme) => ({
  something: {
    fontWeight: 700,
    color: '#FF0000'
  }
});

export default styles;

上述代码中,color 属性可以正常生效,但 font-weight 无法生效,添加 !important 可以解决,但问题出现前无需该声明也能正常覆盖样式。浏览器检查器中可以看到自定义样式类已成功挂载,同时生成的类名为 .Something-something-1 而非预期的 .Something-something。


解决方案

  • 若使用 Mui v5.0.4,需匹配以下版本依赖:
"@emotion/react": "^11.5.0",
"@emotion/styled": "^11.3.0",
"@mui/material": "^5.0.4",
"@mui/icons-material": "^5.0.3",
"@mui/styles": "^5.0.1",
  • 在 App.js 中使用 Mui 提供的 Box、Grid 等组件包裹根元素,修改后代码如下:
import React from "react";
import { Box } from "@mui/material";

import Something from "./Something/Something";

export default function App() {
  return (
    <Box>
      <Something />
    </Box>
  );
}

上述修复经验证可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:15:06