通过反应路由器中的道具传递功能 [英] Pass function by props in react router

查看:81
本文介绍了通过反应路由器中的道具传递功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我知道如何在反应路由器中传递道具,例如string类型.但是当我尝试传递功能道具时,我遇到了一个问题.在我的孩子部分,这个道具是"undefined".

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".

我的链接示例:

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

索引props是一个数字,所以我可以在子组件上获取它,但不能在decreaseIndexProject props上获取.

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

我使用PropType:

I use PropType :

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

我的路由器组件:

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

Maby还有另一种传递函数的方式吗?谢谢您的帮助.

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

推荐答案

您可以使用Link like这样将功能作为位置状态传递

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>

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

现在in Content,您可以像this.props.location.state.decrease

这篇关于通过反应路由器中的道具传递功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆