简体   繁体   中英

React Router dynamic pass down props

My goal is to pass a value from one component to another with the following code: So let's say I'm at example.com/iamhere and I go to example.com/anotherpage I would like to pass the value of this.state.myProp to that other route.

I'm working on a project with some existing code and I have this:

getRoutes = routes => {
  return routes.map((prop, key) => {
    if (prop.layout === "/admin") {
      return (
    <Route
      path={prop.layout + prop.path}
      component={prop.component}
      key={key}
      myProp={this.state.myProp}
    />
      );
    } else {
      return null;
    }
  });
};

I need to pass a prop down, just as an example something like this:

<Route
  path={prop.layout + prop.path}
  component={prop.component}
  key={key}
  myProp={this.state.myProp}
/>

Notice the addition of myProp I wish to pass this value to the next route it goes to. According to a post on git hub . It would be like I did above then in child route I'd use this.props.route.myProp. However that doesn't work, it appears as undefined.

This has been suggested:

<Route exact path="/" render={props => <Component {...props} something={this.state.myProp}/>}/>

But how can I pass the dynamic route component listed in the above code to it?

Any idea how I can achieve it?

一种选择是使用React Router的render prop而不是component

<Route exact path="/" render={props => <Component {...props} something={this.state.myProp}/>}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM