react Child component not receiving props [duplicate]

旧街凉风 提交于 2019-12-24 09:18:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!