Pass function by props in react router

半世苍凉 提交于 2019-12-24 07:16:02

问题


I know how to pass props in the react router like string type for example. But I have a problem when I try to pass props of function. On my children component, this props is "undefined".

Exemple of my Link :

<Link to={'/Content/' + this.props.index + '/' + this.props.decreaseIndexProject}>Page n°1</Link>

The index props is a number, so I can get it on my children component, but not the decreaseIndexProject props.

I use PropType :

NavBar.propTypes = {
   indexProject: PropTypes.number,
   decreaseIndexProject: PropTypes.func
};

My router component :

<Router>
  <Switch>
    <Route path="/Content/:index/:decrease" exact name="content" component={Content} />
  </Switch>
</Router>

Maby there is an other way to pass a function ? Thank you for your help.


回答1:


You can pass the function as location state with Link like

<Link to={{
   pathname: '/Content/' + this.props.index
   state: {decrease: this.props.decreaseIndexProject}
}}>Page n°1</Link>

and

<Router>
  <Switch>
    <Route path="/Content/:index" exact name="content" component={Content} />
  </Switch>
</Router>

Now in Content you can use it like this.props.location.state.decrease




回答2:


@Shubham Khatri's answer is right but also don't forget passing the location to your component otherwise your location.state will be undefined.

<Route
      path="/Content/:index"
      render={props => (<ComponentName location={props.location} {...props}/>)}
 />


来源:https://stackoverflow.com/questions/50235503/pass-function-by-props-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!