【问题标题】:Is there a way to create a ColoredCheckbox component?有没有办法创建 ColoredCheckbox 组件?
【发布时间】:2019-10-15 14:48:26
【问题描述】:

我正在尝试创建一个可重复使用的 Material-ui 彩色复选框组件, 您将十六进制颜色传递给组件,它会影响复选框的颜色。

到目前为止,我得到了这个,但我想不出一种将颜色传递给 withStyles 的方法......

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

如果您有任何提示,请提前致谢。

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您可以使用 function for the value 在样式中利用道具。

    这是一个如何实现此功能的工作示例:

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

    这会将颜色默认为theme.palette.text.secondary,因为那是default Checkbox behavior

    【讨论】:

    • 非常感谢,我自己几乎找到了解决方案,但我忘记在组件中添加 { color, ...other } !像魅力一样工作
    猜你喜欢
    • 1970-01-01
    • 2011-11-26
    • 2014-04-15
    • 2020-05-28
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多