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

Material UI组件自定义样式无法生效问题咨询

问题原因

你当前安装的@mui/material为v5版本,而你引入的makeStyles来自v4版本的@material-ui/styles,跨大版本的样式方案互不兼容,v5组件的内置样式优先级高于v4的makeStyles生成的样式,因此你的自定义样式会被覆盖,在DevTools中会显示为被划掉的无效样式。

解决方法

方案1:适配v5版本的makeStyles(兼容旧写法)

  1. 先卸载v4的旧样式包:
npm uninstall @material-ui/styles
  1. 安装v5版本的样式包:
npm install @mui/styles
  1. 修改导入路径即可正常使用:
// 替换原有导入语句
import { makeStyles } from '@mui/styles';

方案2:使用v5内置sx属性(官方推荐,无需额外安装包)

直接在按钮组件上通过sx属性写自定义样式,不需要单独定义样式钩子,还支持直接编写交互态样式:

<Button
  sx={{
    fontSize: 60,
    backgroundColor: "red",
    '&:hover': {
      backgroundColor: "darkred"
    }
  }}
  onClick={() => console.log("you clicked me")}
  type="submit"
  color="secondary"
  variant="contained"
  endIcon={<KeyboardArrowRightIcon />}
>
  Submit
</Button>

方案3:使用v5的styled API(适合复用样式场景)

如果需要在多个地方复用自定义按钮样式,可以用styled API封装:

import { styled } from '@mui/material/styles';
import { Button } from '@mui/material';

const CustomBtn = styled(Button)({
  fontSize: 60,
  backgroundColor: "red",
});

// 组件内直接使用封装后的按钮
<CustomBtn
  onClick={() => console.log("you clicked me")}
  type="submit"
  color="secondary"
  variant="contained"
  endIcon={<KeyboardArrowRightIcon />}
>
  Submit
</CustomBtn>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:09:00