Material-UI switch 组件选中时如何覆盖样式?

问题描述 投票:0回答:3

我想控制开关组件的颜色,无论是选中时还是未选中时。默认情况下它是红色的。当开关状态为

checked: true
时,我希望“球形旋钮”为黄色,而当它为
checked: false

时,我希望它为灰色

必须使用

createMuiTheme
ThemeProvider
实现样式由于我的项目的性质,我不能直接在组件上使用类。

我在这里尝试遵循他们自定义紫色旋钮的样式示例:https://codesandbox.io/s/x8bz8 资料来源:https://material-ui.com/components/switches/

不幸的是,我无法弄清楚如何在检查球时控制球的颜色(它总是回落到默认的红色)。我在选中和未选中时都成功设置了轨道的颜色,而且我还能够在未选中时设置球的颜色。有人能帮我弄清楚如何在球被选中时应用颜色样式吗?

我做了一个CodeSandbox,我一直在搞乱:https://codesandbox.io/s/material-demo-b6153

 const theme = createMuiTheme({
    overrides: {
      MuiSwitch: {
        switchBase: {
          color: "#ccc", // this is working
          "&$checked": { // this is not working
            color: "#f2ff00"
          }
        },
        track: { // this is working
          opacity: 0.2,
          backgroundColor: "#fff",
          "$checked$checked + &": {
            opacity: 0.7,
            backgroundColor: "#fff"
          }
        }
      }
    }
  });

  return (
    <ThemeProvider theme={theme}>
      <FormGroup>
        <FormControlLabel
          control={
            <Switch
              checked={state.checkedA}
              onChange={handleChange}
              name="checkedA"
            />
          }
          label="Custom color"
        />
      </FormGroup>
    </ThemeProvider>
  );

我也试过这个:

checked: {
  "& + $bar": {
    opacity: 1.0,
    backgroundColor: "rgb(129, 171, 134)" // Light green, aka #74d77f
  }
},

在这个回答中提出了一个有点类似的问题:如何在选中时正确使用 MUISwitch“栏”颜色的主题覆盖?但这似乎不管什么原因都不起作用,可能是 MUI 版本的差异或者因为在

createMuiTheme
.

中创建时样式不同
javascript css reactjs material-ui
3个回答
19
投票

开关默认使用二次色

然后在

colorSecondary
CSS 中控制拇指的颜色。以下是该类的默认样式

  /* Styles applied to the internal SwitchBase component's root element if `color="secondary"`. */
  colorSecondary: {
    '&$checked': {
      color: theme.palette.secondary.main,
      '&:hover': {
        backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
        '@media (hover: none)': {
          backgroundColor: 'transparent',
        },
      },
    },
    '&$disabled': {
      color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800],
    },
    '&$checked + $track': {
      backgroundColor: theme.palette.secondary.main,
    },
    '&$disabled + $track': {
      backgroundColor:
        theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white,
    },
  },

您可以使用以下方法调整主题中选中的颜色(显示覆盖拇指和轨道):

  const theme = createMuiTheme({
    overrides: {
      MuiSwitch: {
        switchBase: {
          // Controls default (unchecked) color for the thumb
          color: "#ccc"
        },
        colorSecondary: {
          "&$checked": {
            // Controls checked color for the thumb
            color: "#f2ff00"
          }
        },
        track: {
          // Controls default (unchecked) color for the track
          opacity: 0.2,
          backgroundColor: "#fff",
          "$checked$checked + &": {
            // Controls checked color for the track
            opacity: 0.7,
            backgroundColor: "#fff"
          }
        }
      }
    }
  });

Edit customize Switch via theme


对于 MUI v5

对于v5,传递给

createTheme
的对象的结构改变了。另一个变化是
primary
现在是默认颜色而不是
secondary
,所以需要覆盖
colorPrimary
样式而不是
colorSecondary

这是 v5 的等效代码:

import React from "react";
import FormGroup from "@mui/material/FormGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import { createTheme, ThemeProvider } from "@mui/material/styles";

export default function CustomizedSwitches() {
  const [state, setState] = React.useState({
    checkedA: true
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setState({ ...state, [event.target.name]: event.target.checked });
  };

  const theme = createTheme({
    components: {
      MuiSwitch: {
        styleOverrides: {
          switchBase: {
            // Controls default (unchecked) color for the thumb
            color: "#ccc"
          },
          colorPrimary: {
            "&.Mui-checked": {
              // Controls checked color for the thumb
              color: "#f2ff00"
            }
          },
          track: {
            // Controls default (unchecked) color for the track
            opacity: 0.2,
            backgroundColor: "#fff",
            ".Mui-checked.Mui-checked + &": {
              // Controls checked color for the track
              opacity: 0.7,
              backgroundColor: "#fff"
            }
          }
        }
      }
    }
  });

  return (
    <ThemeProvider theme={theme}>
      <FormGroup>
        <FormControlLabel
          control={
            <Switch
              checked={state.checkedA}
              onChange={handleChange}
              name="checkedA"
            />
          }
          label="Custom color"
        />
      </FormGroup>
    </ThemeProvider>
  );
}

Edit customize Switch via theme


9
投票

试试这个

const useStyles = makeStyles((theme) => ({  
    switch_track: {
        backgroundColor: "#f50057",
    },
    switch_base: {
        color: "#f50057",
        "&.Mui-disabled": {
            color: "#e886a9"
        },
        "&.Mui-checked": {
            color: "#95cc97"
        },
        "&.Mui-checked + .MuiSwitch-track": {
            backgroundColor: "#4CAF50",
        }
    },
    switch_primary: {
        "&.Mui-checked": {
            color: "#4CAF50",
        },
        "&.Mui-checked + .MuiSwitch-track": {
            backgroundColor: "#4CAF50",
        },
    },
}));

<Switch
  classes={{
    track: classes.switch_track,
    switchBase: classes.switch_base,
    colorPrimary: classes.switch_primary,
  }}
  color={!disabled ? "primary" : "default"}
  checked={value}
  onChange={handleChange}
  name="<your_name>"
  disabled={disabled}
/>


0
投票

MUI v5 的答案

export const lightTheme = createTheme({
  components: {
    MuiSwitch: {
      styleOverrides: {
        switchBase: {
          color: "#E60060",
          "&.Mui-checked": {
            color: "#16DF97"
          }
        },
      },
    },
  },
}

交替

<Switch
 name="mySwitch"
 checked={isChecked}
 onChange={handleChange}
 sx={{
  "&.MuiSwitch-root .MuiSwitch-switchBase": {
    color: "red"
  },

  "&.MuiSwitch-root .Mui-checked": {
   color: "green"
  }
 }}
/>

© www.soinside.com 2019 - 2024. All rights reserved.