typescript - 使用 Material-ui 和 react-router-dom withStyles withRouter 访问 props.classes 的打字稿错误
问题描述
我正在努力让 material-ui 的主题与 Typescript 中的 react-router-dom 一起使用。在访问 classes.root 时render()
,我得到TypeError: Cannot read property 'root' of undefined,但我无法弄清楚我是如何错误地合并/传递道具。谁能看到我做错了什么?提前谢谢了。
相关代码如下:
const styles = (theme: Theme) =>
createStyles({
root: {
maxWidth: 345,
},
});
interface HomeProps extends RouteComponentProps, WithStyles<typeof styles> {
classes: any;
}
export class Home extends React.Component<HomeProps, HomeState> {
constructor(props: HomeProps) {
super(props);
}
render() {
const { classes } = this.props;
// classes.root is undefined...
}
}
export default withRouter(withStyles(styles)(Home));
编辑添加:这个问题的答案没有解决这个问题:Typescript error when using withRouter(withStyles(styles)(ComponentName))
解决方案
代码中存在一些语法错误,这可能是原因。
WithStyles<typeof styles>
给出this.props.classes
它的类型,你不需要也不应该用classes: any;
.
这对我有用
const styles = (theme: Theme) =>
createStyles({
root: {
maxWidth: 345,
},
});
interface HomeProps extends RouteComponentProps, WithStyles<typeof styles> {}
type HomeState = any;
export class Home extends React.Component<HomeProps, HomeState> {
// constructor(props: HomeProps) {
// super(props);
// }
render() {
const { classes } = this.props;
return <div className={classes.root}></div>
}
}
推荐阅读
- javascript - 如果所有子 div 都被隐藏,如何隐藏父 div?
- kubernetes - 如何创建自定义 istio 入口网关控制器?
- java - Spring事务中的方法调用传播
- python - 尝试——除了挣扎
- scala - SPARK:在slave上加载master的目录
- javascript - 如何为 AmChart 生成的 PDF 自定义页眉和页脚?
- python - 通过 Python 的 Bitbucket 服务器 REST API
- c# - 如何通过 node.js 或 c# 从比特币区块链网络获取最新交易
- apache-spark - 无法指向使用来自 spark 的配置单元创建的外部表
- javascript - Firebase 消息传递服务工作人员点击处理程序不起作用