[英]React Material UI: this.props undefined when using withStyles and React Router
In the Parent Component, this.props exists and can find { classes } just fine.在Parent Component中,this.props存在,可以找到{classes}就好了。 However, in the Child Component, this.props is undefined and { classes } cannot be found.
但是,在子组件中,this.props 未定义,无法找到 { classes }。 Both are wrapped in a HOC, but the Child Component is rendered via React Router.
两者都包装在 HOC 中,但子组件是通过 React Router 呈现的。 Relevant code below, please let me know if you need any more context:
下面的相关代码,如果您需要更多上下文,请告诉我:
Parent:家长:
import React, { Component } from "react";
import { withStyles } from '@material-ui/core/styles';
...
import styles from "../../assets/ParentPage/styles";
import theme from "../../assets/theme";
import LandingPageCard from './ParentPageCard';
import { Grid, ThemeProvider } from "@material-ui/core";
import { ChildComponent } from "../../components/NRLMSIS/MsisForm";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export class ParentPage extends Component {
constructor(props) {
super(props);
}
render() {
const { classes } = this.props;
return (
<ThemeProvider theme={theme}>
<Router>
<Grid
container
spacing={4}
className={classes.gridContainer}
justify="center"
>
<Grid item xs={12} sm={6} md={4}>
<Link to="/child">
<LandingPageCard />
</Link>
</Grid>
</Grid>
<Switch>
<Route path="/child" component={ChildComponent} />
</Switch>
</Router>
</ThemeProvider>
);
}
}
Child:孩子:
import React, {Component} from "react";
...
import theme from "../../assets/theme";
import styles from "../../assets/ChildCompnent/styles";
export class ChildCompnent extends Component {
constructor(props) {
super(props);
render() {
const { classes } = this.props;
console.log("PROPS: ", this.props); // this.props == undefined
return (
<Grid container component="main" className={classes.root}>
<CssBaseline/>
</Grid>
);
}
}
}
export default withStyles(styles)(ChildCompnent);
you did export default and the import is with {}
, this is works because you added export to the class, but you have another export (default) with the styles... do:您确实导出默认值并且导入是使用
{}
,这是有效的,因为您将导出添加到 class,但是您有另一个导出(默认)与 styles... 做:
import ChildComponent from "../../components/NRLMSIS/MsisForm";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.