Badge1.def">
当使用多个样式组件时,顶部的组件会覆盖其他默认道具。
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只有变体:“标准”默认道具。它跳过max:无穷大
我怎样才能让所有的defaultProps从每一个级别
发布于 2022-03-21 09:42:17
当您使用情感通过多个styled
调用对组件进行样式化时,情感会将样式层折叠到单个包装组件中,而不是在第一个包装器周围添加额外的包装器。情绪保留上一个包装器中的defaultProps。,但当设置Badge2.defaultProps
时,您将覆盖它。
可以使用以下语法保留任何以前的defaultProps
:
Badge2.defaultProps = {
...Badge2.defaultProps,
variant: 'standard'
}
下面是一个示例,演示每个styled
包装的默认道具会发生什么。这个修复是用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>
);
}
https://stackoverflow.com/questions/71556007
复制