在React-Router中使用Link传递道具

Har*_*man 1 javascript ecmascript-6 reactjs react-router

您好我正在尝试Details使用React Router的链接组件将Props传递给组件.我不想Detail在页面上显示Component,它应该在单击按钮时呈现,但是当新的Component呈现时,url应该看起来像'/ details/KvhNJecsqr6JFMSRTS'.

 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
Run Code Online (Sandbox Code Playgroud)

这是我的路由器的东西

<BrowserRouter>
          <div>
              <Route name='details' path='/details/:cardId' component={Details}/>
            </div>
          </div>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

hier是我的Details组成部分:

    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;
Run Code Online (Sandbox Code Playgroud)

Val*_*ean 11

如果想让你的新路由像/ details /:cardId,那么我想这应该足够了:

<Link to={`/details/${this.props.cardId}`} />
Run Code Online (Sandbox Code Playgroud)

但是,如果您想添加一些额外的属性,那么根据文档,您可以在以下位置传递它们location.state:

<Link to={{
  pathname: `/details/${this.props.cardId}`,
  state: { 
    cardHeading: 'This is a heading',
    cardDesc: 'Description'
  }
}}/>
Run Code Online (Sandbox Code Playgroud)

然后,为了在组件中访问此状态,您可以使用this.props.location.statethis.props.history.location.state