首页 > 解决方案 > 使用 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))

标签: typescriptmaterial-uireact-router-dom

解决方案


代码中存在一些语法错误,这可能是原因。 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>
  }
}
自动补全完成 `classes.root`

https://codesandbox.io/s/zealous-kalam-u3mhx?file=/Home.tsx


推荐阅读