【问题标题】:props-dependent Switch color in Material-UIMaterial-UI 中依赖于道具的切换颜色
【发布时间】:2020-10-15 08:39:41
【问题描述】:

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

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)

但是当试图调整它以便可以通过组件属性设置颜色时,它就不起作用了。事件以下代码(仅是伪动态)呈现到默认开关:

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

我想我一定做错了什么,但不知道是什么。

【问题讨论】:

    标签: javascript reactjs material-ui uiswitch


    【解决方案1】:

    如果您必须使用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} />;
    });
    


    你也可以使用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
          }}
        />
      );
    }
    

    【讨论】:

    • 谢谢,它确实解决了我的问题。您对为什么我的解决方案不起作用有任何解释吗?我不明白为什么将color: 'blue 更改为color: props =&gt; 'blue' 会破坏代码。这不是withStyles 通常的工作方式吗?
    • 你引用的文档没有包含任何关于基于 props 适配的信息,所以我看了一下我引用的文档。但是,主要问题似乎是在使用道具时引用本地规则名称checked。事实上,如果您在实现中将&amp;$checked 替换为&amp;.Mui-checked,它应该可以工作。我主要使用makeStyles 来设置组件的样式(使用MUI 时) - 我在这方面忽略了我的示例,并修改了我的答案以演示使用makeStyles 传递道具。
    猜你喜欢
    • 2021-05-18
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多