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

时间:2020-09-19 23:09:45

标签: reactjs material-ui formik jss formik-material-ui

我正在尝试使用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, 0, 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>
);
}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

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