如何向material-ui中的样式组件添加默认道具?

问题描述 投票:0回答:2

如何在 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
2个回答
0
投票

您可以将功能抽象到中间组件中。

import Button, { ButtonProps } from "@mui/material/Button";
import styled from "@mui/material/styles/styled";

export type MyComponentProps = ButtonProps & {
  myNewVariable: string;
};

function MyComponentImpl(props: MyComponentProps) {
  return <Button variant="outlined" {...props} />;
}

export const MyComponent = styled(MyComponentImpl)(
  ({ myNewVariale, theme }) => ({
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    padding: theme.spacing(2),
  }),
);

-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>;
© www.soinside.com 2019 - 2024. All rights reserved.