【问题标题】:Typescript error accessing props.classes with material-ui and react-router-dom withStyles withRouter使用 Material-ui 和 react-router-dom withStyles withRouter 访问 props.classes 的打字稿错误
【发布时间】:2021-08-01 20:56:12
【问题描述】:

我正在努力让 Material-ui 的主题与 Typescript 中的 react-router-dom 一起使用。在render() 中访问 c​​lasses.root 时,我得到 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))

【问题讨论】:

    标签: typescript material-ui react-router-dom


    【解决方案1】:

    代码中存在一些语法错误,这可能是原因。 WithStyles&lt;typeof styles&gt;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>
      }
    }
    

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

    【讨论】:

    • 感谢您的回答,不幸的是这仍然导致相同的错误(TypeError:无法读取未定义的属性'root')
    • 你能用codeandbox重现这个问题吗?因为我没有看到我的错误。
    猜你喜欢
    • 2019-07-11
    • 2020-02-24
    • 2018-06-04
    • 2019-07-19
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2021-06-28
    • 2020-08-12
    相关资源
    最近更新 更多