TypeScript中使用styled()修改Material UI List组件的component属性类型问题
问题原因
当你用styled(List)<ListProps>定义自定义StyledList组件时,ListProps仅包含Material UI List组件的核心业务属性,并不包含组件通用的component多态属性——这个属性用于指定组件渲染的根元素类型,属于Material UI组件的多态扩展能力,不在基础ListProps的类型定义范围内,因此TypeScript判定StyledList不支持传入component参数。
解决方法
方法1:使用完整组件Props类型(推荐)
通过React的ComponentProps<typeof List>获取原生List组件的全部可接受Props类型(包括component在内的所有多态属性),替换原来的ListProps泛型参数:
import { ComponentProps } from 'react'; import { List } from '@mui/material'; import { styled } from '@mui/material/styles'; const StyledList = styled(List)<ComponentProps<typeof List>>({ '& .MuiListItemButton-root': { paddingLeft: 24, paddingRight: 24, }, '& .MuiListItemIcon-root': { minWidth: 0, marginRight: 16, }, '& .MuiSvgIcon-root': { fontSize: 20, }, });
方法2:手动扩展ListProps类型
如果你不想引入ComponentProps,可以直接给ListProps扩展component属性的类型定义:
import { List, ListProps } from '@mui/material'; import { styled } from '@mui/material/styles'; const StyledList = styled(List)<ListProps & { component?: React.ElementType }>({ // 原有样式代码保持不变 });
修改完成后,再使用<StyledList component="nav" disablePadding>就不会出现类型错误了。
内容的提问来源于stack exchange,提问作者hellreaper
相关产品推荐
相关产品推荐

