在新版@material-ui/core中使用withStyles搭配TypeScript遇类型错误
解决Material-UI v1升级中的TypeScript类型错误
你遇到的问题主要来自两个关键点:withStyles泛型参数的误用,以及组件使用时传递了不符合类型要求的classes属性。下面一步步帮你解决:
错误原因拆解
从报错信息能看到,你在使用<Placeholder>时传入了classes: true,但WithStyles<"root">要求classes是一个包含root字段的字符串对象(Record<"root", string>),布尔值完全不匹配。另外,组件结合withStyles时的泛型配置也有逻辑问题。
具体修复方案
1. 修正组件的Props与withStyles泛型配置
withStyles高阶组件会自动为组件注入classes属性,所以你不需要把包含WithStyles的类型传给withStyles的泛型。正确的逻辑是:
- 组件的Props只定义你需要的自定义属性(如
IPlaceholderProps) withStyles的泛型参数传入你的自定义Props,它会自动合并WithStyles类型
修改后的Placeholder.tsx代码:
import * as React from "react"; import { StyleRulesCallback, WithStyles, withStyles } from "@material-ui/core"; export interface IPlaceholderProps { imageUrl: string; } export const STYLES: StyleRulesCallback<"root"> = theme => ({ root: { display: "flex", justifyContent: "center", alignItems: "center" } }); // 组件接收的Props = 自定义属性 + withStyles注入的classes type PlaceholderProps = IPlaceholderProps & WithStyles<"root">; export class Placeholder extends React.Component<PlaceholderProps, {}> { render() { return ( <div className={this.props.classes.root}> <img src={this.props.imageUrl} /> </div> ); } } // withStyles泛型传入自定义Props即可,自动处理classes注入 export default withStyles(STYLES, { withTheme: true })<IPlaceholderProps>(Placeholder);
2. 修正组件的使用方式
确保使用<Placeholder>时不要手动传递classes={true},这个属性是withStyles自动注入的。如果需要自定义样式覆盖,要传递对象类型的配置:
// 错误用法 ❌ <Placeholder classes={true} imageUrl="your-image-url" /> // 正确用法 ✅(无需手动传classes) <Placeholder imageUrl="your-image-url" /> // 可选:自定义样式覆盖 <Placeholder imageUrl="your-image-url" classes={{ root: "your-custom-root-class" }} />
这样调整后,TypeScript的类型错误应该就能完全解决了。
内容的提问来源于stack exchange,提问作者BlisterFingers
相关产品推荐
相关产品推荐

