Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

reactjs - Change the tick color in MuiCheckbox material UI

I can't seem to find a way to change the tick color in Material UI MuiCheckbox

All the Demos show how to change the color of the whole checkbox, but in all of them, the tick is white.

How can I change the color of the tick only?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Below is an approach that seems to work. The gist of the approach is to create a box (via the :after pseudo-element) that is slightly smaller than the icon for the check and has the desired color as the background color. Then place that box behind the "checked" icon.

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>
  );
}

Edit Checkbox custom check color

An alternative approach would be to create a custom icon that includes the desired color for the check and then use it via the checkedIcon property as in the Custom icon example in the demos.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...