【问题标题】:React Toggle Button color attribute反应切换按钮颜色属性
【发布时间】:2020-11-03 20:45:40
【问题描述】:

我正在尝试在 React 中更改 ToggleButton 的颜色属性。

我想做类似的事情 <ToggleButton color='primary' />

ToggleButton API 当前不支持此选项。我发现的一种解决方法是覆盖 MuiToggleButton CSS 类。

const theme = createMuiTheme({
    overrides: {
        MuiToggleButton: {
            root: {
                color: 'rgba(50, 72, 86, 0.38)',
                '&$selected': {
                    backgroundColor: 'rgba(50, 72, 86, 0.12)',
                    color: 'rgba(50, 72, 86, 1)',
                    '&:hover': {
                        backgroundColor: 'rgba(50, 72, 86, 0.15)',
                    },
                },
            },
        },
    },
}

此解决方案会覆盖所有 ToggleButton,因此在某些情况下可能会出现问题。

【问题讨论】:

  • 我不清楚你的问题是什么。

标签: reactjs material-ui


【解决方案1】:

您可以创建自定义切换组件并应用主题中的相应颜色

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";

const useStyles = makeStyles((theme) => ({
  root: (props) => {
    return {
      color: theme.palette[props.color].main
      // some other custom styles
    };
  }
}));

function MyToggleButton(props) {
  const { color, ...other } = props;
  const classes = useStyles({ color });
  return <ToggleButton classes={classes} {...other} />;
}

export default function CustomColorToggle() {
  const [color, setColor] = React.useState("primary");
  const handleColor = (e, value) => setColor(value);
  return (
    <ToggleButtonGroup
      onChange={handleColor}
      value={color}
      exclusive
      aria-label="text alignment"
    >
      <MyToggleButton color="primary" value="primary">
        Primary
      </MyToggleButton>
      <MyToggleButton color="secondary" value="secondary">
        Secondary
      </MyToggleButton>
    </ToggleButtonGroup>
  );
}

https://codesandbox.io/s/custom-color-toggle-7r0mf?file=/demo.js:0-1037

【讨论】:

  • 这正是我想要的!非常感谢:)
  • @Marc-AndréJolicoeur 如果是这样,我会很感激你接受我的回答
猜你喜欢
  • 2011-09-11
  • 2013-06-07
  • 2017-02-07
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多