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

如何修改MUI Switch组件未选中状态的颜色?

自定义MUI Switch未选中状态颜色

MUI的Switch组件确实没有直接的props控制未选中状态的轨道颜色,但可以通过自定义样式来实现,下面是几种可行的方案:

方案1:使用sx属性内联修改(快速直接)

通过sx属性定位未选中状态的轨道元素,直接修改背景色:

<Switch
  color={dataType === "expenses" ? "error" : "secondary"}
  onChange={handleOnSwitch}
  checked={dataType === "expenses"}
  sx={{
    // 定位未选中状态下的轨道
    '&.MuiSwitch-root:not(.Mui-checked) .MuiSwitch-track': {
      backgroundColor: '#2ecc71', // 替换成你需要的颜色,支持hex/rgb/rgba/主题色
    },
  }}
/>

方案2:创建自定义Styled组件(适合复用)

如果多个地方需要使用这个自定义样式的Switch,可以用styled工具封装成组件:

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

const CustomSwitch = styled(Switch)(({ theme }) => ({
  '&.MuiSwitch-root:not(.Mui-checked) .MuiSwitch-track': {
    // 可以使用主题中的颜色,也可以直接写固定值
    backgroundColor: theme.palette.secondary.light,
  },
}));

// 组件使用示例
<CustomSwitch
  color={dataType === "expenses" ? "error" : "secondary"}
  onChange={handleOnSwitch}
  checked={dataType === "expenses"}
/>

方案3:全局修改主题(应用范围内统一生效)

如果想要整个应用的Switch未选中状态都用同一个颜色,可以修改MUI主题:

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

const theme = createTheme({
  components: {
    MuiSwitch: {
      styleOverrides: {
        root: {
          '&:not(.Mui-checked) .MuiSwitch-track': {
            backgroundColor: '#9b59b6',
          },
        },
      },
    },
  },
});

// 用ThemeProvider包裹你的应用根组件
<ThemeProvider theme={theme}>
  {/* 你的应用内容 */}
</ThemeProvider>

注意事项

  • 类名MuiSwitch-track和Mui-checked是MUI Switch的稳定类名,不同版本的MUI基本保持一致;
  • 颜色值支持hex、rgb、rgba,也可以直接引用MUI主题中的调色板颜色(比如theme.palette.primary.main)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:32:50