使用 defaultProps 样式的 React Material UI v5

React Material UI v5 styled with defaultProps

当使用多个样式组件时,最上面的组件会覆盖其他默认属性。

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 只有变体:'standard' 默认道具。它跳过最大值:Infinity

如何保留每个级别的所有 defaultProps

当您使用 Emotion 通过多个 styled 调用设置组件样式时,Emotion 会将样式层折叠到单个包装器组件中,而不是在第一个包装器周围添加额外的包装器。情感 retains the defaultProps from the previous wrapper,但当您设置 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>
  );
}