升级MUI/React/TS后,OverridableComponent无法赋值给ReactNode问题求助
解决TypeScript类型兼容问题
问题根源
你定义的ListItemStyleProps中,component属性的类型设置为ReactNode是错误的。ReactNode用于描述可渲染的内容(比如JSX元素、字符串、null等),而你传入的Link是一个组件类型(函数/类组件),两者类型不匹配,导致TypeScript报错。
解决方案
修正component属性的类型为React.ElementType(或React.ComponentType),这两个类型专门用于表示组件或原生HTML元素的类型,完全兼容MUI的Link组件类型。
修改后的类型定义
import { LinkProps, ListItemButtonProps, } from '@mui/material'; import type { ElementType } from 'react'; type IProps = LinkProps & ListItemButtonProps; interface ListItemStyleProps extends IProps { component?: ElementType; // 替换ReactNode为ElementType to?: string; activeRoot?: boolean; activeSub?: boolean; subItem?: boolean; }
更简洁的方案(推荐)
由于IProps已经继承了ListItemButtonProps,而ListItemButtonProps中的component属性已经自带正确的ElementType类型,你可以直接移除自己定义的component属性,避免重复定义:
import { LinkProps, ListItemButtonProps, } from '@mui/material'; type IProps = LinkProps & ListItemButtonProps; interface ListItemStyleProps extends IProps { to?: string; activeRoot?: boolean; activeSub?: boolean; subItem?: boolean; }
为什么这样有效
ElementType是TypeScript中用于描述组件或原生元素的通用类型,MUI的OverridableComponent(也就是Link的类型)完全兼容该类型,因此传入component={Link}时不会再出现类型不匹配的错误。
内容的提问来源于stack exchange,提问作者margherita pizza
相关产品推荐
相关产品推荐

