【问题标题】:spreading props in makeStyles在 makeStyles 中传播道具
【发布时间】:2021-09-30 18:39:59
【问题描述】:

使用material-ui 的makeStyles,是否有一个选项可以在应用所有样式的对象中传播道具?

即:

const useStyles = makeStyles(theme) => ({
    card: {
      ...props # <- props has stuff like backgroundColor, fontSize etc.
    },
    thisWorks: {
      backgroundColor: (props) => props.backgroundColor,
      fontSize: (props) => props.fontSize,
    }
})

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    是的,这是可能的。查看文档here

    您可以将道具传递给您的 useStyles 钩子。

    由于您将props 作为您在makeStyles 中声明的函数的参数,因此您必须使用函数。但这并不妨碍您使用展开运算符。

    请记住,您需要在最后返回一个对象

    const useStyles = makeStyles((theme) => ({
      // use the spread operator
      card: (props) => ({
        // dynamic styles from props
        ...props,
        // static styles
        border: "1px solid red"
      }),
    
      // more explicit way if you need just specific props
      card2: (props) => {
        const { backgroundColor, color } = props;
        return {
          backgroundColor,
          color
        };
      }
    }));
    ...
    
    const MyComponent = () => {
    
      const myProps = {
        backgroundColor: "#000",
        fontSize: "32px",
      };
    
      const classes = useStyles(myProps)
    
      return (<div className={classes.card}>
          ...
        </div>
      )
    }
    

    这是一个现场示例:

    【讨论】:

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