如何在 MUI 中的自定义样式组件上设置默认属性?目前,我必须在每个我宁愿烘焙的实例上添加
maxWidth="sm"
。
const MyContainer = styled(Container)(({ theme }) => ({
marginTop: theme.spacing(2),
}));
...
<MyContainer maxWidth="sm" /> // what I have
<MyContainer /> // what I want
您可以将功能抽象到中间组件中。
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),
}),
);
对样式组件使用 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>;