当使用多个样式组件时,最上面的组件会覆盖其他默认属性。
import { styled } from '@mui/material/styles'
import { Badge } from '@mui/material'
const Badge1 = styled(Badge)``
// this works if Badge1 is used directly: <Badge1 />
Badge1.defaultProps = {
max: Infinity
}
const Badge2 = styled(Badge1)`` // styled Badge1
// this overrides defaultProps from Badge1. Prop max: Infinity does no apply here
Badge2.defaultProps = {
variant: 'standard'
}
Badge2 只有 variant: 'standard' 默认 Prop 。它跳过最大值:无穷大
如何保留每个级别的所有 defaultProps
最佳答案
当您使用 Emotion 通过多个 styled
调用设置组件样式时,Emotion 会将样式层折叠到单个包装器组件中,而不是在第一个包装器周围添加额外的包装器。情感retains the defaultProps from the previous wrapper ,但是当您设置 Badge2.defaultProps
时,您将覆盖它。
您可以使用以下语法保留任何以前的 defaultProps
:
Badge2.defaultProps = {
...Badge2.defaultProps,
variant: 'standard'
}
下面是一个示例,演示了每个 styled
包装的默认 Prop 会发生什么。使用 StyledAgainWithDefaultRetainExisting
演示了修复。
import styled from "@emotion/styled";
function MyComponent({ className, ...defaults }) {
return <div className={className}>Defaults: {JSON.stringify(defaults)}</div>;
}
MyComponent.defaultProps = {
orig: true
};
const StyledMyComponent = styled(MyComponent)`
background-color: blue;
color: white;
`;
StyledMyComponent.defaultProps = {
styled: true
};
const StyledAgainNoDefaultsAdded = styled(StyledMyComponent)`
background-color: purple;
`;
const StyledAgainWithDefault = styled(StyledMyComponent)`
background-color: green;
`;
StyledAgainWithDefault.defaultProps = {
styledAgain: true
};
const StyledAgainWithDefaultRetainExisting = styled(StyledMyComponent)`
background-color: brown;
`;
StyledAgainWithDefaultRetainExisting.defaultProps = {
...StyledAgainWithDefaultRetainExisting.defaultProps,
styledAgainRetain: true
};
export default function App() {
return (
<div>
<MyComponent />
<StyledMyComponent />
<StyledAgainNoDefaultsAdded />
<StyledAgainWithDefault />
<StyledAgainWithDefaultRetainExisting />
</div>
);
}
关于reactjs - 使用 defaultProps 样式化的 React Material UI v5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71556007/