简体   繁体   English

如何在React Routes 4之间传递道具

[英]How to pass props between React Routes 4

I can't find the way how to send object from one React Route Component to another. 我找不到如何将对象从一个React Route组件发送到另一个的方法。 For example I have container router like this: 例如我有这样的容器路由器:

const App = () => (
  <Router>
    <div>
      <Route exact path="/" component={Home} />
      <Route path="/sections/:id" 
             component={Section} />
    </div>
  </Router>
)

with Home component like this: 使用Home组件是这样的:

const Home = () => {
    const Sections = tilesData.map( (section, index) => (
      <div>
        <img src={section.img} height="200" /><br/>
        <Link to={`/sections/'${section.id}`} >Details for {section.author}</Link>
        <hr/>
      </div>
    ))
    return(
      <div>
          {Sections}
      </div>
    )
}

and I don't understand =\\ how to pass selected object when next route clicked with <Link> . 而且我不理解= \\当使用<Link>单击下一条路线时如何传递所选对象。 Here is example component: 这是示例组件:

const Section = (props) => {
    return(
        <div>
            Section {props.title} 
            <img src={props.img} />
        </div>
    )
}

Here is code example: https://codesandbox.io/s/Mv037AE3 这是代码示例: https : //codesandbox.io/s/Mv037AE3

In react-router v4, we usually do the following to pass in a ProductPage component: 在react-router v4中,我们通常执行以下操作以传递ProductPage组件:

<Route path='/' component={ProductPage} />

When you want to use props, you can prepare a function that returns your component with the desired props. 当您要使用道具时,可以准备一个函数,该函数返回带有所需道具的组件。 Here I'm preparing to pass in a toggleSidebarOn prop: 在这里,我正在准备传递toggleSidebarOn道具:

const MyProductPage = (props) => {
  return (
    <ProductPage 
      toggleSidebarOn={this.toggleSidebarOn.bind(this)}
      {...props}
    />
  );
}

Then you use the render prop of the <Route /> instead of its component prop. 然后,使用<Route />渲染道具而不是其组件道具。 Do not use both and do not use the component prop as this leads to undesired remounting and might break your app (eg for me CSS transitions for the sidebar animation stopped working properly). 请勿同时使用两者,也不要使用组件prop,因为这会导致不希望的重新安装,并且可能会破坏您的应用程序(例如,对我来说,侧边栏动画的CSS过渡停止正常工作)。

Using the render prop for the MyProductPage we can then pass in our toggleSidebarOn prop to its target route: 使用MyProductPage的渲染道具,然后我们可以将toggleSidebarOn道具传递到其目标路线:

<Router>
  <div>
    <Switch>
      <Route exact path="/products" render={MyProductPage} />
      <Route exact path="/perspectives" component={PerspectivePage}/>
      <Route component={NotFound}/>
    </Switch>
  </div>
</Router>

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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