【问题标题】:passing props with Link in React-Router在 React-Router 中使用 Link 传递道具
【发布时间】:2018-04-27 12:34:28
【问题描述】:

您好,我正在尝试使用来自 React Router 的 Link 组件将 Props 传递给 Details 组件。我不想在页面上显示Detail 组件,它应该在单击按钮时呈现,但当新组件呈现时,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

这是我的路由器资料

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

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;

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-router


    【解决方案1】:

    如果希望您的新路线像 /details/:cardId,那么我想这应该足够了:

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

    但是,如果你想添加一些额外的属性,那么根据documentation,你可以在location.state中传递它们:

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

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

    【讨论】:

    • 谢谢,这很有帮助
    【解决方案2】:

    我相信在您的链接代码中应该是这样的:

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

    路线将与您当前拥有的路线相同。

    【讨论】:

    • 对我不起作用。使用示例 , hohohoh 。结果中不产生任何参数
    猜你喜欢
    • 2015-07-18
    • 2021-07-31
    • 1970-01-01
    • 2021-02-24
    • 2018-08-03
    • 2018-05-03
    • 2018-11-20
    • 2021-09-08
    • 2021-05-07
    相关资源
    最近更新 更多