材质用户界面切换按钮-选中后无法更改背景颜色

问题描述

我正在尝试使用Material UI切换按钮,就像单选按钮一样,为用户提供给定问题的2个选择。

它的功能大致上与预期的一样,但是当尝试为每个切换按钮被选择时调整样式时,我无法更改切换按钮的背景颜色。我在ToggleButton组件上使用了类prop,并在该prop中使用了“ selected”规则。 某些css属性(例如padding和boxShadow)有效,但其他属性(包括backgroundColor)无效。我的目标是使“切换”按钮在被选中时具有蓝色背景,但是到目前为止,我无法使它与被选中时的深灰色背景有所不同。

我正在使用React,以及Formik和Formik-Material-UI。这是我的代码:

const useStyles = makeStyles((theme) => ({
  toggleButton: {
    backgroundColor: 'blue',border: [10,'solid','black'],padding: 10,boxShadow: [
      [0,1,'blue'],],}
}));

export function ScheduleAndServices(props) {
  const classes = useStyles(props);

return (

            <Field 
              component={ToggleButtonGroup} 
              name="requestType" 
              type="checkbox" 
              exclusive
            >
              <ToggleButton 
                value="ps" 
                aria-label="Temporary/Occasional" 
                selected={values.requestType === "ps" ? true : false}
                classes={{selected: classes.toggleButton}}
              >Temporary/Occasional   
              </ToggleButton>
              
              <ToggleButton 
                value="reg" 
                aria-label="Regular"
                selected={values.requestType === "reg" ? true : false}
              >Regular
              </ToggleButton>
            </Field>
);
}

解决方法

在您的全局 css 或 scss 文件中尝试:

button.MuiToggleButton-root.Mui-selected {
  background-color: #1f792f !important;
  border-color: #000 !important;
}

,

新建类,不要忘记使用 !important 覆盖“Mui-selected”类的 backgroundColor

classes= useStyle({
newClass { backgroundColor:'red!important'},})

<ToggleButton 
classes={{ 
selected:clasess.newClass,.
.
.
}}
value=''
/>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...