【发布时间】:2021-12-08 07:25:50
【问题描述】:
使用 React / Material UI,我正在尝试将样式应用于一组 ToggleButtons 。
目前我只能为每个 ToggleButton 定义 style 属性以使其工作。
我正在尝试改用className={...},以使代码更好。
但是,我发现这不适用于ToggleButton 组件:
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import useStyles from './styles';
const DashboardSettings = () = {
const classes = useStyles();
return (
<Fragment>
<Paper className={classes.paper} elevation={10}> // here works
<Typography variant="h4" gutterBottom>
Settings
</Typography>
<br />
<br />
<Grid spacing={3} container>
<Grid xs={12} item>
<Grid container>
<Grid item xs={12}>
<p>Holiday(s): </p>
</Grid>
<Grid item xs={1}></Grid>
<Grid item xs={10}>
<ToggleButtonGroup
// value={formats}
onChange={() => {}}
// fullWidth
aria-label="text formatting"
mt={10}
>
<ToggleButton value="mon" className={classes.toggleButton}> // here it has no effect!
<p>Monday</p>
</ToggleButton>
<ToggleButton value="mon" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Monday</p>
</ToggleButton>
<ToggleButton value="tue" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Tuesday</p>
</ToggleButton>
<ToggleButton value="wed" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Wednesday</p>
</ToggleButton>
<ToggleButton value="thu" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Thursday</p>
</ToggleButton>
<ToggleButton value="fri" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Friday</p>
</ToggleButton>
<ToggleButton value="sat" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Saturday</p>
</ToggleButton>
<ToggleButton value="sun" style={{marginRight: "5px", marginLeft: "5px", backgroundColor: "#FCDC00"}}>
<p>Sunday</p>
</ToggleButton>
</ToggleButtonGroup>
</Grid>
<Grid item xs={1}></Grid>
</Grid>
</Grid>
)
}
./styles.js:
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(3),
marginBottom: theme.spacing(3),
padding: theme.spacing(20),
[theme.breakpoints.up(600 + theme.spacing(3) * 2)]: {
marginTop: theme.spacing(6),
marginBottom: theme.spacing(6),
padding: theme.spacing(3),
},
},
toggleButton: {
marginRight: "5px",
marginLeft: "5px",
color: "#000000",
backgroundColor: "#FFFFFF"
},
}));
export default useStyles;
那我怎样才能以一种更简洁的方式将样式应用到这些按钮上呢?
【问题讨论】:
-
这是 css 特异性问题。请参阅this 答案。
标签: css reactjs material-ui classname