【问题标题】:How to prevent passing props to inner styled component如何防止将道具传递给内部样式组件
【发布时间】:2022-01-03 04:42:04
【问题描述】:

我正在尝试在材质 UI 组件之上进行合成,仅通过给定的道具更改样式。

import { Typography } from "@mui/material";
import { styled } from "@mui/system";

type MyTypographyExtraProps = { isEven?: boolean };

export const MyTypography = styled(Typography)<MyTypographyExtraProps>(
  ({ theme, isEven }) => `
   color: ${theme.palette.common.black};

   ::after {
      content: "";
      display: inline-block;
      height: ${theme.spacing(2)};
      width: ${theme.spacing(2)};
      border-radius: ${theme.spacing(2)};
      background-color: ${theme.palette[isEven ? "success" : "error"].main};
   }
  `,
);

styled 函数将我的 isEven 属性传递给 Material Typography 组件,然后 Typography 将它传递给 DOM,所以我收到了警告

警告:React 无法识别 DOM 元素上的 isEven 属性。如果您有意希望它作为自定义属性出现在 DOM 中,请将其拼写为小写 iseven。如果您不小心从父组件传递了它,请将其从 DOM 元素中移除。

如何在传递给排版元素之前省略类型?

我可以制作另一个组件并消除该层中的道具,但我很想知道是否有任何方法可以在没有额外组件的情况下做到这一点。

【问题讨论】:

    标签: typescript material-ui emotion


    【解决方案1】:

    Material docs 建议了一个函数来消除 props 的传递。

    shouldForwardProp:说明必须将哪些道具传递给样式化的给定组件。

    export const MyTypography = styled(MuiTypography, {
      shouldForwardProp: prop => prop !== "isEven", // ⭐
    })<MyTypographyExtraProps>(
      ({ theme, isEven }) => `
       color: ${theme.palette.common.black};
    
       ::after {
          content: "";
          display: inline-block;
          height: ${theme.spacing(2)};
          width: ${theme.spacing(2)};
          border-radius: ${theme.spacing(2)};
          background-color: ${theme.palette[isEven ? "success" : "error"].main};
       }
      `,
    );
    

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 2021-10-28
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2019-09-23
      • 1970-01-01
      • 2019-11-08
      相关资源
      最近更新 更多