Material-UI中与道具有关的开关颜色

问题描述

从Material-UI文档改编为customizing Switch的以下代码允许将开关颜色设置为蓝色:

import React from 'react'

import Switch from '@material-ui/core/Switch'
import {withStyles} from '@material-ui/core/styles'


const ColoredSwitch = withStyles({
  switchBase: {
    '&$checked': {
      color: 'blue',},checked: {},track: {},})(Switch)

Blue switch

但是,当尝试对其进行调整以使颜色可以通过组件属性进行设置时,它根本不起作用。事件以下代码(仅是伪动态的)呈现为认开关:

const ColoredSwitch = withStyles({
  switchBase: {
    '&$checked': {
      color: props => 'blue',})(Switch)

Default switch

我想我一定做错了什么,但不知道该怎么办。

解决方法

如果必须使用withStyles HOC,请遵循以下示例传递道具:https://material-ui.com/styles/basics/#adapting-the-higher-order-component-api

const ColoredSwitch = withStyles({
  switchBase: {
    "&.Mui-checked": {
      color: (props) => props.customchecked
    }
  },checked: {},track: {}
})((props) => {
  const { classes,...other } = props;
  return <Switch classes={{ switchBase: classes.switchBase }} {...other} />;
});

Edit Material demo (forked)


您也可以使用makeStyles

const useStyles = makeStyles({
  switchBaseChecked: {
    "&.Mui-checked": {
      color: (props) => props.color
    }
  }
});

export default function Switches() {
  const props = { color: "green" };
  const classes = useStyles(props);
  return (
    <Switch
      color="primary"
      classes={{
        checked: classes.switchBaseChecked
      }}
    />
  );
}

Edit Material demo (forked)