MUI v5使用withStyles定义AntSwitch组件触发TS2786错误如何解决?
MUI v5 升级后AntSwitch组件TS2786错误解决方案
错误原因
该错误是MUI v5版本中,遗留包@mui/styles导出的withStyles方法类型定义未正确继承被包装原生组件的属性类型,和TypeScript 4.4.4版本的类型校验规则不匹配,导致无法识别返回的AntSwitch为合法JSX组件。
解决方案
方案1(推荐):替换为MUI v5官方推荐的styled API
styled是MUI v5主推的样式方案,类型兼容更好,样式逻辑和你原有写法完全一致,不需要修改组件调用代码:
import { styled } from '@mui/material/styles'; import Switch from '@mui/material/Switch'; const AntSwitch = styled(Switch)(({ theme }) => ({ root: { width: 28, height: 16, padding: 0, display: 'flex', }, switchBase: { padding: 2, color: theme.palette.grey[500], '&$checked': { transform: 'translateX(12px)', color: theme.palette.common.white, '& + $track': { opacity: 1, backgroundColor: theme.palette.primary.main, borderColor: theme.palette.primary.main, }, }, }, thumb: { width: 12, height: 12, boxShadow: 'none', }, track: { border: `1px solid ${theme.palette.grey[500]}`, borderRadius: 16 / 2, opacity: 1, backgroundColor: theme.palette.common.white, }, checked: {}, }));
方案2:保留withStyles写法,手动补充类型断言
如果需要保留原有withStyles的写法,只需在组件导出时手动断言其为合法的Switch组件类型即可:
import { withStyles } from '@mui/styles'; import Switch, { SwitchProps } from '@mui/material/Switch'; const AntSwitch = withStyles((theme) => ({ // 原有样式代码保持不变 }))(Switch) as React.ComponentType<SwitchProps>;
额外校验
如果修改后仍存在报错,检查项目中@types/react、@types/react-dom的版本是否和你项目使用的React版本匹配,升级到对应兼容版本即可解决类型冲突。
内容的提问来源于stack exchange,提问作者Saeed Hemmati
相关产品推荐
相关产品推荐

