【问题标题】:pass material ui styles to component - react将材质 ui 样式传递给组件 - 反应
【发布时间】:2020-07-04 11:16:40
【问题描述】:

我正在使用带有 React 的功能组件,我需要根据状态显示 SVG 图标,并且我想加载相关图标

所以父级将只显示调用:

<icon classes:... , state..></icon>

1-我如何传递样式,如果它不存在并在孩子中使用默认样式?

现在我在父母身上有了类似的东西:

... createStyle
  IconSuccess: {
     fontSize: 20,
      width: 20,
    },
    IconWarning: {
      fontSize: 20,
      width: 20,
    },

但我想要类似的东西:

 icon:{
  width:..
  font ..
  warning: { color}
  success: { color}
 }

then 

<IconChild state={state} classes={{ icon: itemStyle.icon}} />

这只有在我传递特定样式时才有效,例如:

 <IconChild state={state} classes={{ iconWarning: itemStyle.iconWarning}} />


then in the childCOmponent I am doing smth like:


 const classes = useStyles(props);
 if( props.state == 1){
  return <className={`${classes.iconWarning}`} />
 }
 else{
  return  <className={`${classes.iconSuccess}`} />
 }

所以基本上我想了解如何创建一个我可以使用和传递的真正通用组件,并且需要一个状态来选择特定图标以及特定类

我需要 HOC 吗?或不同的方法

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    据我了解,您希望:

    • 重用一些常用属性,例如widthfontSize
    • 自定义渲染其他属性,例如color

    那么这是我的做法:

    • 首先,为常用属性制作新样式。
    • 其次,为每个状态的有条件使用创建新样式。
    • 最后,使用classnames 之类的东西来组合所有类。

    所以这里的主要思想是:不再为每个项目使用一个类,而是为每个项目使用两个类。就是这样!

    const useStyles = withStyles({
      commonProperty: {
        fontSize: '20px',
        width: '20px',
      },
      successOnlyProperty: {
        color: 'green'
      },
      warningOnlyProperty: {
        color: 'orange'
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2019-02-02
      • 2020-09-13
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多