扩展MUI SvgIcon的自定义组件无法识别component属性类型问题
问题根因
你之前的IconProps直接继承了无泛型的SvgIconProps,丢失了MUI SvgIcon内置的、用于支持自定义component属性的泛型能力,导致传入自定义component带来的额外属性(比如framer-motion的variants/initial等)不被类型系统识别。
解决方案
分两步修改Icon.tsx的类型定义:
- 将
IconProps改为支持传入根组件类型的泛型接口,继承带泛型的SvgIconProps - 给经过
React.memo包裹的组件补充泛型类型声明,避免泛型丢失
修改后的完整代码如下:
import React from 'react'; import { SvgIcon, SvgIconProps } from '@mui/material'; import SvgIconMap, { Icons } from './svg'; // 新增泛型参数,支持传入自定义根组件类型 export interface IconProps<RootComponent extends React.ElementType = typeof SvgIcon> extends Omit<SvgIconProps<RootComponent>, 'color'> { icon: Icons; color: string; size?: number | string; height?: number; width?: number; }; // 声明为泛型组件,补充类型断言修复React.memo丢失泛型的问题 const Icon = React.memo( <RootComponent extends React.ElementType = typeof SvgIcon>({ icon, color, height, width, size, sx: psx, ...rest }: IconProps<RootComponent>) => { const Svg = SvgIconMap[icon]; const sx = { color, height: size ?? height, width: size ?? width, stroke: 'currentColor', fill: 'transparent', ...psx, }; return <Svg sx={sx} {...rest} />; } ) as <RootComponent extends React.ElementType = typeof SvgIcon>(props: IconProps<RootComponent>) => React.ReactElement; export default Icon;
验证效果
修改完成后你的原有用法即可正常通过类型校验,如果仍有特殊场景的类型报错,可以手动指定泛型参数明确根组件类型:
<Icon<typeof motion.svg> icon={Icons.CONTEXTE1} size={22} color="text.hint" component={motion.svg} variants={fadeOut} initial="default" animate={isHovered ? 'hover' : 'default'} />
内容的提问来源于stack exchange,提问作者v1s10n_4
相关产品推荐
相关产品推荐

