简体   繁体   中英

passing props with Link in React-Router

Hello i'm trying to pass Props to a Details Component with the Link Component from React Router. I don't want to display the Detail Component on the page, it should render when a button is clicked but also the url should look like this '/details/KvhNJecsqr6JFMSRTS' when the new Component renders.

 class  Card extends Component {
                    render(props){
                    return(
                   <Col xs={12} md={4}>
                    <Thumbnail src="./someiamge">
                      <h3>{this.props.cardHeading}</h3>
                      <p>{this.props.cardDesc}</p>
                        <Button bsStyle="primary">Mieten</Button>&nbsp;
                        <Button bsStyle="default"><Link to='/details' params={{cardId: this.props.cardId}} 'here i wanna pass some props how i do this ?' >Details</Link></Button>
                    </Thumbnail>
                  </Col>

                    )
                  }
                }

export default Card

Here is my Router stuff

<BrowserRouter>
          <div>
              <Route name='details' path='/details/:cardId' component={Details}/>
            </div>
          </div>
</BrowserRouter>

hier is my Details Component:

    class Details extends Component {
      render() {
        return (
          <div >
            <div style={{textAlign: "left"}}>
              <h3>{this.props.cardHeading}</h3>
              <p>{this.props.cardDesc}</p>
              .......
            </div>
          </div>
        );
      }
    }

    export default Details;

If want your new route to be like /details/:cardId, then I guess this should be enough:

<Link to={`/details/${this.props.cardId}`} />

But, if you want to add some extra properties, then according to documentation , you could pass them in the location.state :

<Link to={{
  pathname: `/details/${this.props.cardId}`,
  state: { 
    cardHeading: 'This is a heading',
    cardDesc: 'Description'
  }
}}/>

Then, in order to access this state in your component, you can use the this.props.location.state or this.props.history.location.state

In your link code it should be this, I believe:

<Link to={{ pathname: '/details', query: { cardId: this.props.cardId } }}/>

The Route would be the same as you currently have it.

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