小编典典

在MuiCheckbox材质用户界面中更改刻度颜色

reactjs

我似乎找不到在Material UI MuiCheckbox中更改刻度颜色的方法

所有的演示都展示了如何更改整个复选框的颜色,但是在所有这些示例中,勾号都是白色的。

如何仅更改刻度线的颜色?


阅读 265

收藏
2020-07-22

共1个答案

小编典典

下面是一种似乎可行的方法。该方法的要点是创建一个框(通过:after伪元素),该框比用于检查的图标略小,并且具有所需的颜色作为背景色。然后将该框放在“选中”图标的后面。

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import FormGroup from "@material-ui/core/FormGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";

const CheckboxWithGreenCheck = withStyles({
  root: {
    "&$checked": {
      "& .MuiIconButton-label": {
        position: "relative",
        zIndex: 0
      },
      "& .MuiIconButton-label:after": {
        content: '""',
        left: 4,
        top: 4,
        height: 15,
        width: 15,
        position: "absolute",
        backgroundColor: "lightgreen",
        zIndex: -1
      }
    }
  },
  checked: {}
})(Checkbox);

export default function CheckboxLabels() {
  const [state, setState] = React.useState({
    checkedA: true,
    checkedB: false
  });

  const handleChange = name => event => {
    setState({ ...state, [name]: event.target.checked });
  };

  return (
    <FormGroup>
      <FormControlLabel
        control={
          <CheckboxWithGreenCheck
            checked={state.checkedA}
            onChange={handleChange("checkedA")}
            value="checkedA"
            color="primary"
          />
        }
        label="Custom check color"
      />
    </FormGroup>
  );
}

编辑复选框自定义检查颜色

一种替代方法是创建一个包含所需支票颜色的自定义图标,然后通过该checkedIcon属性使用它,如演示中的“
自定义图标”示例中所示。

2020-07-22