reactjs – React路由器和this.props.children – 如何将状态传递给this.props.children

我第一次使用React-router,而且我不知道如何去思考。以下是我在嵌套路由中加载组件的方法

入口点.js

ReactDOM.render(
    <Router history={hashHistory} >
        <Route path="/" component={App}>
            <Route path="models" component={Content}>
        </Route>
    </Router>,document.getElementById('app')
);

App.js

render: function() {
    return (
      <div>
        <Header />
        {this.props.children}
      </div>
    );
  }

所以我的应用程序的孩子是我发送的内容组件。我使用Flux,我的App.js有状态并监听更改,但我不知道如何将该状态传递给this.props.children 。在使用反应路由器之前,我的App.js明确定义了所有的孩子,所以传递状态是自然的,但我现在看不到如何做。

使用几个React帮助器方法,您可以向this.props.children添加状态,道具和其他任何内容
render: function() {
  var children = React.Children.map(this.props.children,function (child) {
    return React.cloneElement(child,{
      foo: this.state.foo
    })
  })

  return <div>{children}</div>
}

那么你的子组件可以通过道具this.props.foo来访问它。

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...