如何在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
相关产品推荐
相关产品推荐

