2017-02-21 157 views
0

这里有应用程序根组件通过克隆将一个handleHeaderTitle函数传递给其所有子项。 儿童内部组件中,函数在componentWillMount() 中调用,结果根组件根据路由更新标题文本。子组件更改父组件状态

根:

{ 
     this.props.children && 
        React.cloneElement(this.props.children, { 
         handleHeaderTitle: this.handleHeaderTitle 
        }) 
    } 

    handleHeaderTitle(title) { 
     this.setState({ headerTitle: title }); 
    } 

儿童:

componentWillMount() { 
    this.props.handleHeaderTitle("Profile"); 
    } 
    Profile.propTypes = { handleHeaderTitle: React.PropTypes.func }; 

,提供了增加Redux的,因为国家是不是真的局部这里正在从其父一个子组件设置这个权利用例?

我想我需要创建像SET_PROFILE_HEADER和内部减速器这样的动作。但仍然搞清楚如何通知容器根组件,该子组件已更改标题标题

回答

1

要直接回答您的问题,您不需要Redux来解决您的问题。 Redux可以帮助您维护很多状态,或者当您的状态需要反映应用程序中没有亲密共同祖先的部分时。换句话说,如果使用老式的React状态过于繁琐。

对于React中的特定问题,更常见的方法是将您的布局包含在子组件中而不是根中。这避免了试图让孩子控制父母内容的问题。它有助于保留React所关心的“单向数据流”。

class Page extends React.Component { 
    render() { 
    return (
     <div> 
     <div className='profile-header'> 
      { this.props.headerTitle } 
     </div> 
     <div className='profile-content'> 
      { this.props.children } 
     </div> 
     </div>  
    ) 
    } 
} 

class MyFirstPage extends React.Component { 
    render() { 
    return (
     <Page headerTitle='Header Title 1'> 
      <div>My content here</div> 
     </Page> 
    ) 
    } 
} 
+0

感谢Chardy,我使用了侧边栏组件(https://github.com/balloob/react-sidebar),它不会让子组件中定义标题。 – fortm

相关问题