typescript - 如何防止将 Prop 传递给内部样式组件

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

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

样式化函数将我的 isEven 属性传递给 Material Typography 组件,而 Typography 将它传递给 DOM,所以我收到了警告

Warning: React does not recognize the isEven prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase iseven instead. If you accidentally passed it from a parent component, remove it from the DOM element.

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

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

最佳答案

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

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

注意:shouldForwardPropsskipSx 如果你想阻止 sx 和其他 Prop , Prop 没有完全对齐同时 Prop 。
有关详细信息,请参阅 this github issue

https://stackoverflow.com/questions/70102062/

相关文章:

laravel - created_at 和 updated_at 不会在 laravel 中插入时

python - Matplotlib Colormaps——为每个图形/线条/主题选择不同的颜色

c - 在两个源文件之间拆分类似函数的宏调用

node.js - 每当我要登录或注册 strapi 405(方法不允许)消息出现

linux - NeoVim 缺少 Python 支持

encryption - 如何在 Web 浏览器中使用 Webauthn/CTAP HMAC-Sec

python - Ursina Python 引擎 : Lighting, 阴影和光晕效果

clojure - 撤消覆盖 Clojure 中的内置函数

c++ - 多线程段故障析构函数

php - arc diff(Arcanist)因 env : php: No such file