扩展MUI ListItemButtonProps自定义props遇TypeScript错误求解
错误原因及解决方法
错误原因
- 基础属性集不包含
component:你直接继承的ListItemButtonProps是Material UI ListItemButton的核心属性集合,component这类用于自定义根元素的扩展属性并不在其中——这类属性是由MUI的OverridableComponent泛型机制提供的,属于组件的可覆盖扩展属性,不在基础Props定义里。 - 类型定义未关联完整组件属性:自定义组件的类型没有正确复用ListItemButton的完整可覆盖类型体系,导致TypeScript无法识别
component作为合法属性。
解决方法
方法一:复用MUI的类型工具(推荐,符合MUI规范)
利用MUI提供的OverridableTypeMap和OverridableComponent工具类型,在ListItemButton的基础类型上添加自定义属性,自动包含component、sx等扩展属性:
import { ListItemButton, OverridableComponent, OverridableTypeMap } from '@mui/material'; // 定义自定义组件的类型映射,整合原组件属性与自定义state type SidebarListItemButtonTypeMap = OverridableTypeMap< {}, { props: ListItemButton['props'] & { state: 'active' | 'inactive'; }; } >; // 生成包含所有合法属性的类型(含component) type SidebarListItemButtonProps = OverridableComponent<SidebarListItemButtonTypeMap>['props']; const SidebarListItemButton = ({ state, ...props }: SidebarListItemButtonProps) => { // 可根据state添加自定义逻辑,比如激活态样式 const buttonProps = { ...props, sx: { ...props.sx, backgroundColor: state === 'active' ? '#f0f0f0' : 'transparent' } }; return <ListItemButton {...buttonProps} />; };
方法二:直接扩展组件完整属性类型
通过React的ComponentProps工具类型,获取ListItemButton的完整属性集合(包括component),再添加自定义属性:
import { ListItemButton } from '@mui/material'; import type { ComponentProps } from 'react'; // 扩展ListItemButton的全部属性,添加自定义state interface SidebarListItemButtonProps extends ComponentProps<typeof ListItemButton> { state: 'active' | 'inactive'; } const SidebarListItemButton = ({ state, ...props }: SidebarListItemButtonProps) => { return <ListItemButton {...props} />; };
内容的提问来源于stack exchange,提问作者gremo
相关产品推荐
相关产品推荐

