将功能属性传递给子组件(通过链接和路由组件)

时间:2020-04-09 12:38:52

标签: javascript reactjs

我正在使用带有Rails API后端的纯React。

我正在从API提取数据并将状态存储在Trips组件中。我有一个Link组件,可以在其中将状态传递给NewTrip组件,但是<Link>不允许我传递函数。

我能够通过位于“ ./routes/Index”的Route组件上的render方法将函数传递给NewPage。

但是如何从Trips组件传递函数?作为道具传递到组件时,它要容易得多,Router似乎在挡路!

'routes / Index.js'

export default (
  <Router>
    <Switch>
      <Route path="/" exact component={Home} />
      <Route path="/trips" exact component={Trips} />
      <Route path="/trip" render={(routeProps)=><NewTrip {...routeProps} />}/>
      <Route path="/trip/:id" exact component={Trip} />
      <Route path="/trip/:id/cost" exact component={NewCost} />
      <Route path="/trip/:id/edit" exact component={EditTrip} />
    </Switch>
  </Router>
);

'components / Trips'

class Trips extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      trips: []
    }

    this.addTrip = this.addTrip.bind(this);
  }

  addTrip(trip) {
    const {trips} = this.state;
    trips.push(trip);
    this.setState({ trips: trips});
  }

  render(){
    return(
      <Link
        to={{
          pathname: "/trip",
          state: {trips: trips, onAddTrip={this.addTrip}} // not allowed,
// but I want to pass this function to the 
// Component which is rendered by the Route in Index.js
        }}
        className="btn custom-button">
          Create New Trip
      </Link>
    )
  }
}

2 个答案:

答案 0 :(得分:1)

我认为您应该"Germany"组件中的lift state up,并将其放在“ routes / Index.js”中。 (它现在必须是一个组件,而不仅仅是出口)。

'routes / Index.js'

Germany

'components / Trips'

Trips

最好在export default class Routes extends React.Component { constructor(props) { super(props); this.state = { trips: [] } this.addTrip = this.addTrip.bind(this); } addTrip(trip) { const {trips} = this.state; trips.push(trip); this.setState({ trips: trips}); } render() { return ( <Router> <Switch> <Route path="/" exact component={Home} /> <Route path="/trips" exact component={Trips} /> <Route path="/trip" render={(routeProps)=> <NewTrip addTrip={this.addTrip} trips={this.state.trips} {...routeProps} /> }/> <Route path="/trip/:id" exact render={(routeProps)=> <Trip addTrip={this.addTrip} trips={this.state.trips} {...routeProps} /> }/> <Route path="/trip/:id/cost" exact component={NewCost} /> <Route path="/trip/:id/edit" exact component={EditTrip} /> </Switch> </Router> ); } } 组件中设置更高的状态,但是您没有提供,所以必须这样做:)

答案 1 :(得分:0)

您可以在React Router Link中使用state传递函数。

    <Link
        to={{
          pathname: "/trip",
          state: {trips: trips, onAddTrip: this.addTrip}
        }}
        className="btn custom-button">
          Create New Trip
    </Link>

然后在/trip中,您将检索并使用如下函数:

this.props.location.state.addTrip();