问题
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