如何实现自定义Radio-Button点击激活时切换背景颜色
解决选中状态Radio按钮背景色修改问题
要实现选中时高亮显示,你可以利用MUI的Mui-checked类选择器,在FormControlLabel的sx属性中添加选中状态的样式规则。由于你已经隐藏了原生Radio组件,选中状态会直接作用在FormControlLabel上,针对这个类设置样式即可达到效果。
修改后的完整代码
<FormControl sx={{width: '100%'}} > <RadioGroup aria-labelledby="demo-controlled-radio-buttons-group" name="controlled-radio-buttons-group" value={value} onChange={handleChange} sx={{width: '100%', display:'flex', gap:1 }} > <FormControlLabel value="male" control={<Radio sx={{ display: 'none' }} />} label={ <Typography sx={{ fontSize: 16, fontWeight: 'bold' }}> Male </Typography> } sx={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'center', color: 'blue', '&:hover':{ backgroundColor: '#03a9f4', color: 'white' }, // 新增选中状态样式 '&.Mui-checked': { backgroundColor: '#03a9f4', color: 'white' } }}/> <FormControlLabel value="female" control={<Radio sx={{ display: 'none' }} />} label={ <Typography sx={{ fontSize: 16, fontWeight: 'bold' }}> Female </Typography> } sx={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'center', color: 'blue', '&:hover':{ backgroundColor: '#03a9f4', color: 'white' }, // 新增选中状态样式 '&.Mui-checked': { backgroundColor: '#03a9f4', color: 'white' } }}/> </RadioGroup> </FormControl>
关键说明
&.Mui-checked是MUI为处于选中状态的FormControlLabel自动添加的类名,通过这个选择器可以精准控制选中时的背景色、文字颜色等样式。- 你可以根据需求替换
backgroundColor和color的取值,自定义高亮效果。
内容的提问来源于stack exchange,提问作者Zurcemozz
相关产品推荐
相关产品推荐

