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

如何在Material-UI中保留禁用Button组件的原有背景色

实现方案

实现原理

MUI 默认的 .Mui-disabled 类优先级高于按钮 color/variant 对应的样式类,会统一覆盖颜色、背景、边框等属性为 theme.palette.action 下的全局灰色值。我们只要将这些被强制覆盖的属性重置为 unset,样式就会回退到按钮原本对应配色的样式,再叠加透明度即可实现需求。

完整主题配置

import { createTheme } from '@mui/material/styles';

const customTheme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: "none",
          boxShadow: "none",
          "&.Mui-disabled": {
            // 清除默认禁用状态的统一灰色覆盖
            color: "unset",
            backgroundColor: "unset",
            // 若使用outlined变体按钮,需添加下面这行保留原有边框颜色
            borderColor: "unset",
            // 仅叠加0.7透明度
            opacity: 0.7,
            // 保留默认禁用状态无阴影的效果,不需要可删除
            boxShadow: "none"
          }
        }
      }
    }
  }
});

效果说明

该配置全局生效,无需修改现有按钮代码,也无需封装自定义组件,自动适配所有 color(primary/secondary/error/info 等)、所有 variant(contained/outlined/text)的按钮,禁用状态会完全保留原有配色,仅叠加透明度效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:39:00