我正在尝试在React中更改ToggleButton
的颜色属性。
我想做类似的事情
<ToggleButton color='primary' />
ToggleButton
API当前不支持此选项。我发现一种解决方法是覆盖MuiToggleButton
CSS类。
const theme = createMuiTheme({
overrides: {
MuiToggleButton: {
root: {
color: 'rgba(50, 72, 86, 0.38)',
'&$selected': {
backgroundColor: 'rgba(50, 72, 86, 0.12)',
color: 'rgba(50, 72, 86, 1)',
'&:hover': {
backgroundColor: 'rgba(50, 72, 86, 0.15)',
},
},
},
},
},
}
此解决方案会覆盖所有ToggleButton
,因此在某些情况下可能会出现问题。
答案 0 :(得分:0)
您可以创建自定义的Toggle组件并应用主题中的相应颜色
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";
const useStyles = makeStyles((theme) => ({
root: (props) => {
return {
color: theme.palette[props.color].main
// some other custom styles
};
}
}));
function MyToggleButton(props) {
const { color, ...other } = props;
const classes = useStyles({ color });
return <ToggleButton classes={classes} {...other} />;
}
export default function CustomColorToggle() {
const [color, setColor] = React.useState("primary");
const handleColor = (e, value) => setColor(value);
return (
<ToggleButtonGroup
onChange={handleColor}
value={color}
exclusive
aria-label="text alignment"
>
<MyToggleButton color="primary" value="primary">
Primary
</MyToggleButton>
<MyToggleButton color="secondary" value="secondary">
Secondary
</MyToggleButton>
</ToggleButtonGroup>
);
}
https://codesandbox.io/s/custom-color-toggle-7r0mf?file=/demo.js:0-1037