【问题标题】:How do I style a toggle switch with useStyles instead of withStyles in Material UI?如何在 Material UI 中使用 useStyles 而不是 withStyles 设置切换开关的样式?
【发布时间】:2021-04-11 04:46:35
【问题描述】:

我在 Material UI 中有一个输入表单开关,我希望轨道和按钮在打开时显示为红色,就像在 this example 中一样。 Material UI 网站上的所有switch styling examples 都使用 withStyles,但我不确定为什么不能使用 useStyles 代替?是否可以使用 useStyles 做到这一点?

这是我的尝试,但不起作用!

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';

const useStyles = makeStyles(theme => ({
  switchBase: {
    '&$checked + $track': {
      backgroundColor: 'red',
    },
  },
}));

export default function SwitchesSize() {
const classes = useStyles()
  const [checked, setChecked] = React.useState(false);

  const toggleChecked = () => {
    setChecked((prev) => !prev);
  };

  return (
    <FormGroup>
      <FormControlLabel
        control={<Switch size="small" checked={checked} onChange={toggleChecked} />}
        label="Small"
        classes={{ switchBase: classes.switchBase }}
      />
    </FormGroup>
  );
}

非常感谢您的帮助:)

凯蒂

【问题讨论】:

    标签: css reactjs material-ui


    【解决方案1】:

    要使用useStyles 设置Switch 的样式,需要定位根组件。

    <FormGroup>
      <FormControlLabel
        control={
          <Switch
            color="default"
            classes={{
              track: classes.switchTrack,
              switchBase: classes.switchBase,
            }}
            size="small"
            checked={checked}
            onChange={toggleChecked}
          />
        }
        label="Small"
        // classes={{ switchBase: classes.switchBase }}
      />
    </FormGroup>
    

    useStyles 对象:-

    const useStyles = makeStyles((theme) => ({
        switchTrack: {
            backgroundColor: "#000"
        },
        switchBase: {
            color: "#000",
            "&.Mui-checked": {
                color: "green"
            },
            "&.Mui-checked + .MuiSwitch-track": {
                backgroundColor: "green"
            }
        },
    }));
    

    工作沙盒链接:-https://codesandbox.io/s/prod-wave-e9otk

    【讨论】:

    • 非常感谢您的回复,但这似乎对我不起作用?我编辑了您的沙箱以检查,如果您将背景颜色从红色更改为蓝色,它会保持红色,所以我认为默认情况下它必须是红色的。由于我的主题,我的默认为灰色,我想覆盖它。你知道怎么把你的变成蓝色吗?非常感谢
    • 嘿,我已经更新了答案。很抱歉最后一次没有交叉检查答案。我以为只有const classes = useStyles() 行不见了。我已经更新了答案。
    • 这太完美了!非常感谢 Rajiv - 我永远不会意识到该类适用于控件内的开关。再次感谢您为我节省了大量时间! :)
    猜你喜欢
    • 2018-11-20
    • 2019-11-21
    • 2021-01-06
    • 2020-11-16
    • 2019-09-21
    • 2019-06-14
    • 2021-03-09
    • 2021-02-19
    • 2022-08-10
    相关资源
    最近更新 更多