【问题标题】:How to pass props with react-router using onClick methods如何使用 onClick 方法通过 react-router 传递道具
【发布时间】:2019-06-02 15:07:24
【问题描述】:

我是 react 新手,甚至是 react-router 的新手,我创建了一个 react 应用程序,其中包含一些路由,但有些路由需要相同的数据(道具)。当按下当前页面上的按钮时,我想通过 onClickEvent 传输这些道具。我读到了一些尝试,例如将按钮上的 onClick 侦听器绑定到

之类的方法
handleOnClick(){    
  this.props.history.push('/booking')
 ))

重定向到名为“预订”的路线。但是我怎样才能将我当前页面的单个道具或整套道具传递给这个新页面?有什么解决方案吗?如何访问重定向路线上的道具?

这是我的 Index.js,更多路线将很快添加:

const routing = (
 <Router>
   <div>
    <Route exact path="/" component={App} />
     <Route path="/booked" component={Booked} />
   </div>
 </Router>
 );

ReactDOM.render(routing, document.getElementById("root"));

路由树应如下所示:我的 App.js 中有一个主视图,用于呈现 BookingItems 的组件。在 Bookingitem 中,我有多个道具。当我预订一些项目时,我应该被重定向到我的 Booked.js 组件。

在任何 BookingItems 中,我都有一个按钮可以重定向到 Booked.js。

预订项目:

onButtonClick() {
  this.props.history.push("/booked");
 }

render(){
 return(
          <div className="alignCenterDiv">
            <button
              onClick={this.onButtonClick.bind(this)}
              align="center"
              className="buttonBooking"
            >
              Buchen
            </button>
          </div>
)}

预订: 在这里,我想访问我在 BookingItems 中拥有的任何道具,或者我在预订项目中创建的任何道具,以将其传递给 Booked。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    如果您使用以下方式重定向:

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

    然后,在/booking 页面中,您可以像这样访问变量:

    console.log(this.props.location.state)
    /*
      {
        myProp: '...',
        foo: 'bar'
      }
    */
    

    【讨论】:

    • 这就是我想做的!非常感谢先生! :)
    【解决方案2】:

    你可以这样做:

    你的路线

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

    点击

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

    预订组件

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

    有关其他选项,您可以阅读以下内容:How to get parameter value from query string

    另一种选择(在问题更新后听起来更好)是使用 redux (或类似的东西)。当您单击按钮时,您发送一个操作以将全局状态中的 selectedBookingItem 设置为单击的项目。然后导航(查看 react-router-redux)。 Booking 组件连接到 redux,并且 selectedBookingItem 映射到 prop (mapStateToProps)。

    【讨论】:

    • 感谢您的尝试。它有效,但不能满足我想要做的事情,因为这样我只能传递一个道具(在这种情况下:id),而且我也不想在我的链接中看到那个道具(..:/booking/12345)。传递多个道具的任何其他解决方案?
    • @Alex,路径 "/booking/:id/:name/:someOtherProp" 怎么样?
    • @Alex,如果您不想在路径中看到这些数据,那么您可能需要一些状态管理,例如 redux。您需要哪些属性来路径到组件?
    • 我编辑了我的主要帖子,希望能更好地理解。我需要传递名称、目的地、价格等道具。
    • @Alex,祝你好运。希望我的回答对你有所帮助。
    猜你喜欢
    • 2019-08-09
    • 1970-01-01
    • 2019-04-28
    • 2018-05-13
    • 2018-11-20
    • 2021-05-16
    • 2020-01-15
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多