MUI v5中使用styled自定义Button绑定react-router-dom Link的类型报错如何解决
问题原因
MUI v5的styled工具默认生成的组件类型不会自动保留原MUI组件的多态(polymorphic)类型定义,原Button组件支持的component、to这类动态组件属性没有被继承到你自定义的MyButton上,所以TypeScript会报错找不到对应属性。
修复方案
方案1:给styled调用显式传入泛型参数(推荐,适用绝大多数场景)
直接在定义MyButton的时候,声明它继承MUI Button的所有属性,包括多态相关的类型:
import { Button, ButtonProps, styled, alpha } from "@mui/material"; // 给styled(Button)加上<ButtonProps>泛型,保留所有原生Button的属性支持 const MyButton = styled(Button)<ButtonProps>(({ theme }) => ({ color: 'white', margin: theme.spacing(1), backgroundColor: alpha(theme.palette.common.white, 0.25), '&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.35), }, }));
改完之后MyButton就完全支持原生Button的所有属性,包括component、to等react-router相关属性,不需要额外修改其他业务代码。
方案2:全局配置styled属性继承(适合大量自定义MUI组件的场景)
如果项目里有很多自定义的MUI组件,不想每个都单独加泛型,可以全局配置styled的类型继承规则:
import { createStyled } from "@mui/material/styles"; // 全局创建styled实例,默认保留所有MUI组件的多态属性 const styled = createStyled({ defaultProps: { enableColorScheme: true } }); // 后续定义所有自定义MUI组件都不需要再加泛型 const MyButton = styled(Button)(({ theme }) => ({ // 样式代码 }));
效果验证
修改后你可以直接正常使用原有调用代码,TypeScript不会再报component不存在的错误:
<MyButton component={Link} to="/"> My Button </MyButton>
内容的提问来源于stack exchange,提问作者RouteMapper
相关产品推荐
相关产品推荐

