【问题标题】:How to pass props to child components in react-router tree如何将道具传递给反应路由器树中的子组件
【发布时间】:2016-10-11 17:10:12
【问题描述】:

我有一个由 react-router 组成的路由模型。我想知道如何在此设置中的组件之间传递道具 - 有可能吗?

   <Route path='/' component={Layout}>
      <IndexRoute component={Home} />
      <Route path='/users' component={Users} />
      <Route path='/posts' component={Posts} />
      <Route path='/albums' component={Albums} />
      <Route path='/about' component={About} />
   </Route>

例如,我在 Layout 组件中初始化了我的状态(想法是它的所有子项都可以访问该状态);我如何将 state 值传递给它们,并在通过 props 传递的父组件中触发函数?

这可能吗,如果组件直接嵌套在它的父级中,还是我在路由方面以错误的方式考虑这个?如果有,是否有替代解决方案?

任何帮助表示赞赏

【问题讨论】:

  • 您可能需要考虑使用redux
  • 谢谢,我也很怀疑。还没有开始使用 redux,但现在可能是时候弄脏我的手了 :)

标签: reactjs react-router state parent


【解决方案1】:

是的,这是可能的。您可以在Layout 组件中使用context。这是 ES6 中的一个示例:

export default class Layout extends React.Component {

    static childContextTypes = {
        layoutState: React.PropTypes.object
    }

    getChildContext() {
        return {layoutState: this.state};
    }

}

然后只需在子/孙组件中声明上下文:

export default class Users extends React.Component {

    static contextTypes = {
        layoutState: React.PropTypes.object
    }

    render() {
        const {layoutState} = this.context;
        // then just use your layoutState and return
    }
}

【讨论】:

  • 谢谢,但在阅读了官方文档后,似乎强烈建议不要使用此功能 a) 因为 API 可能会更新,并且 b) 它会使您的代码更难理解(不完全确定为什么会这样,但我会相信他们的话!)。有没有更稳定的方法来实现这一点?例如,使用 Redux 会更容易吗?
  • 嗯,我认为没有其他方法可以初始化 Layout 中的状态并将变量传递给 Layout 的子项。由于子组件在 Layout 实例化之前已经实例化,因此 react-router 可以将它们作为 props.children 传递给 Layout
猜你喜欢
  • 2020-03-26
  • 2015-09-01
  • 2016-09-30
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多