我想控制开关组件的颜色,无论是选中状态还是未选中状态。默认情况下为红色。我希望开关状态为“球形旋钮”时为黄色,而当开关状态为“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
。
切换默认为使用辅助颜色。
然后在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: {
colorSecondary: {
"&$checked": {
color: "#f2ff00"
}
},
}
}
});
这是展示此内容的沙箱的修改版本:https : //codesandbox.io/s/material-demo-8x66o?file=/ demo.tsx: 663-766
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句