You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免自定义props透传到MUI styled内部组件触发DOM属性警告

解决方法

有两种无需额外封装组件层的实现方案:

方案1:使用shouldForwardProp手动过滤

MUI styled 支持传入第二个配置参数,通过shouldForwardProp回调指定哪些prop需要透传给底层组件:

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

type MyTypographyExtraProps = { isEven?: boolean };

export const MyTypography = styled(Typography, {
  // 过滤自定义的isEven prop,不传入底层组件
  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};
   }
  `,
);

如果有多个需要过滤的自定义prop,可以批量判断:

{
  shouldForwardProp: (prop) => !['isEven', 'customProp1', 'customProp2'].includes(prop as string)
}

方案2:使用Transient Props自动过滤

MUI默认支持$前缀的prop作为样式专属prop,这类prop会自动被过滤,不会透传给底层组件,不需要额外配置:

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

// 自定义prop加$前缀
type MyTypographyExtraProps = { $isEven?: boolean };

export const MyTypography = styled(Typography)<MyTypographyExtraProps>(
  // 直接使用带$前缀的prop计算样式
  ({ 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};
   }
  `,
);

内容的提问来源于stack exchange,提问作者amirhe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:06:03