将状态传递给子组件作为属性

时间:2016-04-17 02:20:27

标签: reactjs react-router

我目前正在学习React路由器v1.0,并且我很难将状态传递给子组件作为属性。

App.js

  getInitialState: function(){
  return {
    status: 'disconnected',
    title: ''
  },
  ...
  ,
  render: function(){
    return (
      <div>
        <Header title={this.state.title} status={this.state.status}/>
        {React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}
      </div>
    );

Client.js

var routes = (
  <Router history={hashHistory}>
  <Route path="/" component={App}>
    <IndexRoute component={Audience} />
    <Route path ="speaker" component={Speaker} />
  </Route>
</Router>
);

Audience.js

render: function(){
  return(
  <div>
    <h1>Audience</h1>
    {this.props.title || "Welcome Audience"}
    </div>
 );
}

Speaker.js

render: function(){
    return(
    <div>
     <h1>Speaker:</h1>
     {this.props.status || "Welcome Speaker!"}
    </div>
  );
  }

而不是这样做:

{React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}

对于使用https://facebook.github.io/react/docs/jsx-spread.html运算符的React.cloneElement,是否有类似的内容:

<RouteHandler {...this.state}/>

TLDR; 基本上我想将整个州传递给我的路线组件,而不是单独定义它们。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

嗯,简单的答案就是没有。

正如你在this comment中看到的那样 - 有一些方法可以实现这种行为(你正在做的就是其中之一),也许你已经看过所有这些,但我不会建议您使用其中任何一种,除非确实有必要。

您应该在以下主题中检查有关它的讨论:

https://github.com/reactjs/react-router/issues/1857

https://github.com/reactjs/react-router/issues/1531

  

@ryanflorence [React-router的合着者]

     

您应该将路线组件视为应用的切入点   不知道或不关心父母的,父母不应该   知道/关心孩子们。

通常,处理这些案例的最佳方法是使用类似redux的内容 - 应用程序的整个状态存储在对象树中,并且可以在路径组件中轻松共享。 /强>