Is there a way to create a ColoredCheckbox component?

只愿长相守 提交于 2019-12-11 06:18:59

问题


I'm trying to create a reusuable material-ui colored checkbox component, you pass a hex color to the component and it affects the checkbox's color.

I got this so far but i can't think of a way to pass a color to withStyles...

const WhiteCheckbox = withStyles({
  root: {
    color: '#fff',
    '&$checked': {
      color: '#fff',
    },
  },
  checked: {},
})(props => <Checkbox color="default" {...props} />);

Thanks in advance if you have any tip to make it work.


回答1:


You can leverage props within styles by using a function for the value.

Here is a working example of how you could implement this:

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

const ColoredCheckbox = withStyles(theme => ({
  root: {
    color: ({ color }) => (color ? color : theme.palette.text.secondary),
    "&$checked": {
      color: ({ color }) => (color ? color : theme.palette.text.secondary)
    }
  },
  checked: () => ({})
}))(({ color, ...other }) => <Checkbox color="default" {...other} />);

function App() {
  return (
    <div className="App">
      <ColoredCheckbox />
      <ColoredCheckbox color="red" />
      <ColoredCheckbox color="green" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This defaults the color to theme.palette.text.secondary since that is the default Checkbox behavior.



来源:https://stackoverflow.com/questions/58397369/is-there-a-way-to-create-a-coloredcheckbox-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!