【问题标题】:How to pass custom props to Material-UI component using makeStyles/withStyles?如何使用 makeStyles/withStyles 将自定义道具传递给 Material-UI 组件?
【发布时间】:2021-12-07 23:58:08
【问题描述】:

如何将自定义道具传递给 MUI 组件?假设我想通过 customProps='red' 来改变组件的背景颜色?

在我的情况下,我需要为按钮添加不同的背景颜色,并且我想添加如下内容:

<SubmitButton
  variant={"outlined"}
  customBackground={'red'} // this prop
>
  Submit
</SubmitButton>

我应该使用makeStyles吗?

Here 是密码箱。

【问题讨论】:

    标签: reactjs material-ui styled-components


    【解决方案1】:

    在你用withStyles定义的样式中

    root: {
      backgroundColor: (props) => props.customBackground
      {...}
    },
    

    然后在withStylesHOC创建的组件中:

    <SubmitButton customBackground="red"
    

    如果你想设置一组样式属性,你可以传递一个回调,返回一个样式对象而不是一个值(docs):

    root: ({ mode }) => ({
      ...(mode === "dark" && {
        backgroundColor: "black",
        color: "lightgray",
        "&:hover": {
          backgroundColor: "darkblue"
        }
      }),
      ...(mode === "light" && {
        backgroundColor: "white",
        color: "black",
        "&:hover": {
          backgroundColor: "lightblue"
        }
      }),
    })
    

    然后在您的自定义组件中传递 prop 以应用动态样式:

    <SubmitButton mode="light">light</SubmitButton>
    <SubmitButton mode="dark">dark</SubmitButton>
    

    我应该使用 makeStyles 吗?

    makeStyleswithStyles 是相同的,只是makeStyles 返回一个不能在类组件中使用的钩子。如果你使用函数式组件,你应该使用makeStyles,因为它更容易插入(更容易添加或删除样式)。

    【讨论】:

    • 非常感谢。有用。还有一个问题,如何添加一组特定属性?假设我想要一个重置按钮有不同的颜色、悬停等。我可以按照你写的方式来做……但是可以吗,还是有更正确的方法?我的意思是如何用一堆道具定义“变体”并将其分配给按钮
    • @qweezz 查看我更新的答案和代码框,您实际上可以更简单地做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 2020-01-10
    • 2020-12-22
    • 2020-12-26
    • 2020-05-08
    相关资源
    最近更新 更多