【问题标题】:Pass function by props in react router在反应路由器中通过道具传递功能
【发布时间】:2018-10-18 12:24:33
【问题描述】:

我知道如何在反应路由器中传递道具,例如 string 类型。但是当我尝试传递函数道具时遇到问题。在我的孩子组件上,这个道具是"undefined"

我的链接示例:

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

索引道具是一个数字,所以我可以在我的子组件中获取它,但不是decreaseIndexProject 道具。

我使用 PropType :

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

我的路由器组件:

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

也许还有其他方法可以传递函数?感谢您的帮助。

【问题讨论】:

  • 你将一个函数连接成一个字符串?我不明白你要做什么
  • 嗯,我不这么认为,我只是在路由器上传递了两个不同类型的参数,不是吗?
  • 不,您正在尝试将indexdecreaseIndexProject 连接到字符串'/Content/',如果decreaseIndexProject 是一个函数,这是不可能的。

标签: javascript reactjs function react-router-v4 react-props


【解决方案1】:

您可以使用 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 一样使用它

【讨论】:

    【解决方案2】:

    @Shubham Khatri 的回答是正确的,但也不要忘记将位置传递给您的组件,否则您的 location.state 将是未定义的。

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

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2017-07-12
      • 2023-01-18
      • 2021-05-24
      • 1970-01-01
      • 2019-08-15
      • 2021-06-27
      • 2021-09-13
      • 2020-11-16
      相关资源
      最近更新 更多