MUI v5使用styled()包裹ListItemButton时报to/component属性不存在的TS错误
问题根源
该类型报错的根源是MUI的styled工具默认只会保留原组件(这里是ListItemButton)的基础属性定义,当通过component属性切换底层渲染组件时,TypeScript无法自动推断新组件对应的额外属性(比如Link组件的to属性),因此会提示to/component不存在。
解决方案
只需要在创建styled组件时,通过泛型显式声明该组件支持传入自定义component及对应属性即可,MUI官方提供了标准化的Extend*泛型工具来做这件事,不需要手动拼接类型。
修复后完整代码
import React from "react" import { Avatar, Link, ListItemAvatar, ListItemButton, styled, ExtendListItemButton, // 新增导入MUI提供的ListItemButton扩展泛型 } from "@mui/material" // 给styled组件传入泛型,指定支持传入Link作为component,自动合并Link的属性 const ListItemButtonLink = styled(ListItemButton)<ExtendListItemButton<typeof Link>>( ({ theme }) => ({ // 你的样式代码 }) ) interface LinkedListItemProps { path: string } export const LinkedListItem = ({ path }: LinkedListItemProps) => { return ( <ListItemButtonLink key={42} dense to={path} component={Link}> <ListItemAvatar> <Avatar>A</Avatar> </ListItemAvatar> Here Be Item </ListItemButtonLink> ) }
简化写法(无需额外导入泛型)
如果只需要临时适配当前场景,也可以手动声明需要的额外属性,写法更直观:
const ListItemButtonLink = styled(ListItemButton)<{ component?: React.ElementType; to?: string; }>(({ theme }) => ({ // 你的样式代码 }))
内容的提问来源于stack exchange,提问作者TheDiveO
相关产品推荐
相关产品推荐

