【问题标题】:How to add default props to styled components in material-ui?如何在 material-ui 中为样式化组件添加默认道具?
【发布时间】:2022-06-18 21:05:28
【问题描述】:

如何在 MUI 中为自定义样式的组件设置默认道具?目前,我必须在我宁愿加入的每个实例上添加maxWidth="sm"

const MyContainer = styled(Container)(({ theme }) => ({
  marginTop: theme.spacing(2),
}));

...

<MyContainer maxWidth="sm" /> // what I have

<MyContainer /> // what I want

【问题讨论】:

    标签: typescript material-ui styled-components


    【解决方案1】:

    对样式化的组件使用 attrs。在下面的示例中,默认使用“sm”变体容器。

    文档:https://styled-components.com/docs/api#attrs

    const MyContainer = styled(Container).attrs((p) => ({
      maxWidth: p.maxWidth || "sm"
    }))(({ theme }) => ({
      marginTop: theme.spacing(2)
    }));
    
    const App = () => <MyContainer>1</MyContainer>;
    

    【讨论】:

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