扩展MUI5 Button支持component prop时类型提示失效如何解决?
问题根因
- 定义的泛型
C extends React.ElementType未设置默认值,当你不主动传入componentprop时,TS无法自动推断泛型类型,只能 fallback 为任意类型,导致所有原生Button属性的类型推导失效,既不会触发提示也不会做校验。 ButtonProps<C, { component?: C }>的第二个泛型参数属于冗余写法,MUI的组件Props类型已经内置了component属性的类型处理逻辑,额外传入会干扰内部类型推导。
修正代码
import Button, { ButtonProps } from '@mui/material/Button'; import React from 'react'; // 给泛型设置默认值为MUI Button默认的元素类型'button' export type MyButtonProps<C extends React.ElementType = 'button'> = ButtonProps<C> & { myOtherField: string; }; // 组件泛型同步设置默认值 export function MyButton<C extends React.ElementType = 'button'>(props: MyButtonProps<C>) { const { myOtherField, ...buttonProps } = props; return <Button {...buttonProps} />; }
效果验证
- 不传入
component属性时,TS会自动使用默认的button类型,所有MUI Button原生属性、HTML button属性都会正常提示,类型校验正常生效。 - 主动传入
component属性时,TS会自动根据传入的组件类型推导泛型,给出对应组件的属性提示,不会触发类型报错。
如果需要支持ref透传,可使用React.forwardRef包裹组件并透传泛型定义即可。
内容的提问来源于stack exchange,提问作者Alper
相关产品推荐
相关产品推荐

