问题
This is parent component:
class App extends Component {
defaultState = {
test: "hello"
};
constructor(props) {
super(props);
this.state = this.defaultState
}
render() {
return (
<Router>
<Switch>
<Route key="home" path="/" test={this.state.test} component={HomeScreen}/>
</Switch>
</Router>
);
}
}
and this is the child component:
class HomeScreen extends Component{
constructor(props) {
super(props);
}
render(){
return(
<div>
<p>Hello, Welcome to the app. {this.props.test}</p>
</div>
)
}
}
The prop test
is not printed as in the child component.
What could be the issue?, have been on this for long
回答1:
You can use render function in
Example:
<Route path="/abc" render={()=><TestWidget num="2" someProp={100}/>}/>
Checkout this doc on render function
Your render function should look like this:
render() {
return (
<Router>
<Switch>
<Route key="home" path="/" render={(props) => <HomeScreen test={this.state.test} {...props} />}/>
</Switch>
</Router>
);
}
来源:https://stackoverflow.com/questions/48346237/react-child-component-not-receiving-props