如何防止将 props 传递给内部样式组件

Ami*_*imi 3 emotion typescript material-ui

我正在尝试在材质 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};
   }
  `,
);
Run Code Online (Sandbox Code Playgroud)

styled 函数将我的isEvenprops 传递给 Material Typography 组件,Typography 将其传递给 DOM,所以我收到警告

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

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

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

Ami*_*imi 11

Material文档建议使用一个函数来消除 props 的传递。

\n

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

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

注意:如果您想同时阻止和其他道具,则shouldForwardProps和道具不会完全对齐。\n有关更多信息,请参阅此 github 问题skipSxsx

\n