如何更改拇指开关react js的颜色



我有一个开关,我想把圆圈的颜色改成深灰色。我在互联网上看了看,但我不太明白如何使用组件文档中的css规则。有人能帮我吗!?这是我的代码:

const ThemeToggle = () => {
const { theme, setTheme } = useContext(ThemeContext);
const handleThemeToggle = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
if (theme === 'light') {
document.body.classList.add('darkBackground');
} else {
document.body.classList.remove('darkBackground');
}
};

return <div>
<Switch
uncheckedIcon={false}
checkedIcon={false}
onColor={'#eee'}
onChange={handleThemeToggle}
checked={theme === 'light'}
/>
</div>
}
export default ThemeToggle;

组件文档:https://mui.com/material-ui/api/switch/

我用这个开关来改变模式。因此,在灯光模式下,拇指将变灰。在暗模式下,缩略图将是白色

**主题上下文:

export const ThemeContext = React.createContext({} as IThemeContext);
const App: React.FC = () => {
const storedTheme = localStorage.getItem("darkTheme");
const [theme, setTheme] = useState(storedTheme);

useEffect(() => {
localStorage.setItem("darkTheme", theme);
})
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<CssBaseline />
<BrowserRouter>
<GlobalStyle />
<AppRouter />
</BrowserRouter>
</ThemeContext.Provider>
);
};

尝试覆盖此类:

.MuiSwitch-colorSecondary.Mui-checked {
color: green; // any color you want
}

示例:https://codesandbox.io/s/material-ui-switch-forked-2plbik?file=/src/components/SwitchContainer.jsx

我创建了以下代码沙盒,在这里你可以看到我如何在这个网站上用CSS全局类更改Switch组件的颜色:https://mui.com/material-ui/api/switch/#css提供+你的情况下,你只需要它的黑暗背景:

.darkBackground {
background-color: #404042;
color: gray;
}
.light {
background-color: #fff;
color: #000;
}
.MuiSwitch-switchBase .MuiSwitch-thumb {
color: purple;
}
.MuiSwitch-switchBase + .MuiSwitch-track {
background-color: purple;
}
.darkBackground .MuiSwitch-switchBase.Mui-checked .MuiSwitch-thumb {
color: white;
}
.darkBackground .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track {
background-color: white;
}

我无法更改上下文,这就是为什么我问你是否可以分享它,但如果你在这个演示中让上下文发挥作用,它应该像你期望的那样发挥作用:

演示:

https://codesandbox.io/s/charming-shannon-36bl1m?file=/src/styles.css

最新更新