Okt*_*can 4 reactjs material-ui styled-components react-props
当使用多个样式组件时,最上面的一个会覆盖其他默认的 props。
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'
}
Run Code Online (Sandbox Code Playgroud)
Badge2 只有变体:“标准”默认道具。它跳过最大值:无穷大
如何保留每个级别的所有默认道具
当您使用 Emotion 通过多次调用来设置组件的样式时styled,Emotion 会将样式层折叠到单个包装器组件中,而不是在第一个包装器周围添加额外的包装器。Emotion保留了前一个包装器中的 defaultProps,但您在设置时会覆盖它Badge2.defaultProps。
您可以defaultProps使用以下语法保留任何先前的内容:
Badge2.defaultProps = {
...Badge2.defaultProps,
variant: 'standard'
}
Run Code Online (Sandbox Code Playgroud)
下面的示例演示了每次styled包装时默认 props 会发生什么情况。该修复通过 进行演示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>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3618 次 |
| 最近记录: |