简体   繁体   中英

How to pass props in Link in react-Router?

I have a hotel's page and I want to create a Page for each single hotel .
How could I pass props in Link in react-Router?
And how can I use it in my hotel Component?

you can add params to the link

<Link 
  to={{
     pathname: "/path/to/",
     state:{...props}
  }}> 
></Link>

use it like that

const params = this.props.location.state

React Router's <Link> component will decorate any component (or an anchor <a> tag) with routing functionality, passing any extra prop you provide. From its documentation, you can see how it ends up rendering the component.

Here is a link to the source code

Any extra prop you define on the body of the <Link> React Router will pass to the provided component or anchor tag. You could do something like this:

Using the default <Link> component:

const hotels = [{id: 1, name: 'hotel 1'}, {id: 2, name: 'hotel 2'}]

function LinkList({hotels}) {
  return (
    hotels.map(hotel => <Link to={`/hotel/${id}`} hotel={hotel} /> 
  )
} 

Using a custom component : *

const FancyLink = React.forwardRef(({hotel, ...props}, ref) => (
  <a ref={ref} {...props}>{hotel.name} {props.children}</a>
))

function LinkList({hotels}) {
  return (
    hotels.map(hotel => <FancyLink to={`/hotel/${id}`} hotel={hotel} /> 
  )
} 

* Taken from React Router's docs

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