简体   繁体   中英

react-router: Best way to pass props to nested route components in react-router ^2.0.0?

Precursor:

I am refactoring two components, Photos.js and PhotoDetailsModal.js . Originally they had a relationship like this:

<Photos>
   <PhotoDetailsModal/>
</Photos>

my route '/photos' looked like the following, and Photos.js simply controlled the the rendering of PhotoDetailsModal internally through state and a little bit of data-gathering:

<Route path="photos" component={Photos}/>

If I want to decouple these two components and make a route like this:

<Route path="photos" component={Photos}>
  <Route path=":photoId" component={PhotoDetailsModal}>
  </Route>
</Route>

How do I pass props into the PhotoDetailsModal component? Prior to this re-design, Photos.js simply handled all the data gathering and just passed expanded photo data to <PhotoDetailsModal/> internally through some props.

I do know that inside Photos.js I will eventually use {this.props.children} to render PhotoDetailsModal , I just want to know how to do all of my data-passing from <Photos/> to <PhotoDetailsModal/> using this new routing .

With v2/3 of React Router, you will have to use cloneElement to re-render the this.props.children element with the desired props. Basically, your code will look like this:

render() {
  const { children } = this.props
  return (
    <div>
      { children && React.cloneElement(children, { other: 'foo' }) }
    </div>
  )
}

The documentation for React Router includes this passing props to children example app which does the same thing.

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