Passing custom props to router component in react-router v4

后端 未结 1 2087
时光取名叫无心
时光取名叫无心 2020-11-22 12:38

I\'m using React Router to create a multi page app. My main component is and it renders all of the routing to to child components. I\'m trying to p

相关标签:
1条回答
  • 2020-11-22 13:10

    You can pass props to the component by making use of the render prop to the Route and thus inlining your component definition. According to the DOCS:

    This allows for convenient inline rendering and wrapping without the undesired remounting explained above.Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop receives all the same route props as the component render prop

    So you can pass the prop to component like

     <Route path="/" exact render={(props) => (<Home test="hi" {...props}/>)} />
    

    and then you can access it like

    this.props.test 
    

    in your Home component

    P.S. Also make sure that you are passing {...props} so that the default router props like location, history, match etc are also getting passed on to the Home component otherwise the only prop that is getting passed down to it is test.

    0 讨论(0)
提交回复
热议问题