reactjs - 使用 defaultProps 样式化的 React Material UI v5

标签 reactjs material-ui styled-components react-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'
}

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>
  );
}

Edit styled and defaultProps

关于reactjs - 使用 defaultProps 样式化的 React Material UI v5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71556007/

相关文章:

reactjs - 如何使用refreshControl在React Native ScrollView中刷新?

javascript - 状态更改时,React jsx 数组组件不会重新渲染

javascript - Webpack 使用大型 ES6 模块构建性能缓慢

reactjs - 样式组件中的动态主题

typescript - 样式组件 defaultProps

javascript - react 单选按钮 : checked cycle not aligned

javascript - React中是否可以打印16次

javascript - Material ui 中选项卡的内联样式不会改变颜色

javascript - 如何在 React 中编写一个需要另一个特殊功能的 HOC?

reactjs - 如何在 react js中仅允许文本框中的数字和格式为美国手机号码格式?前 : (224) - 5623 -2365