使用MUI styled方法定制组件时报TypeScript错误TS2739如何解决?
问题原因
你导入的styled来自已废弃的@mui/styles包,该包的类型定义无法正确识别MUI基础组件的Props类型,错误推断组件需要接收number类型的属性,才会要求你传入toFixed等number内置方法。
解决方案
方案1(推荐):更换styled的导入来源
MUI v5及以上版本官方推荐使用@mui/material/styles导出的styledAPI,自带完整的类型推断能力,直接修改导入语句即可:
// 替换前 // import { styled } from "@mui/styles"; // 替换后 import { styled } from "@mui/material/styles";
修改后无需调整其他代码,类型错误会直接消失。
方案2(仅兼容旧项目使用):手动声明组件Props类型
如果你必须保留@mui/styles的使用,可以手动给自定义组件指定Props类型:
import { Button, ButtonProps } from "@mui/material"; import { styled } from "@mui/styles"; const MyButton = styled(Button)<ButtonProps>({ background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)", border: 0, borderRadius: 3, boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)", color: "white", height: 48, padding: "0 30px", });
注意事项
@mui/styles是legacy方案,不支持React 18及以上版本,如果你的项目使用React 18+,必须使用方案1解决,否则还会出现其他运行时异常。
内容的提问来源于stack exchange,提问作者Nawaraj Jaishi
相关产品推荐
相关产品推荐

