How to pass props with react-router using onClick methods

后端 未结 2 1694
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 12:54

Im new to react and even newer to react-router and i create a react app which contains a few routes but some routes need the same data (props). I want to transfer those prop

相关标签:
2条回答
  • 2021-01-03 13:33

    If you redirect using:

    this.props.history.push('/booking', {
      myProp: this.props.myProp,
      foo: 'bar'
    })
    

    Then, in /booking page, you can access the variables like so:

    console.log(this.props.location.state)
    /*
      {
        myProp: '...',
        foo: 'bar'
      }
    */
    
    0 讨论(0)
  • 2021-01-03 13:44

    You can do it like this:

    You route

    <Route path="/booking/:id" .../>
    

    On Click

    handleOnClick(){    
      this.props.history.push('/booking/12345')
     ))
    

    Booking component

    componentDidMount(){
      console.log(this.props.match.params.id);
    }
    

    For alternative options you can read this: How to get parameter value from query string

    Another option (after question update it sounds like a better option) is to use redux (or something similar). When you click on the button you dispatch an action to set selectedBookingItem in global state to the clicked item. Then navigation (look at the react-router-redux). Booking component is connected to the redux and selectedBookingItem is mapped to the prop (mapStateToProps).

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