2015-04-24 82 views
2

我有一个包含一些数据的表,并且表中的每个元素都是一个React类组件。它看起来像这样:从父母状态刷新儿童状态React

Table

我要的是有一个复选框“检查所有”功能(左上复选框)。事情是我不知道如何解决,因为propsstate

我一样,在单个元素组件代码:

getInitialState: function() { 
    return { component: this.props.data }; 
    }, 

render: function() { 
    var data = this.state.component; 
    data = data.set('checked', this.props.data.get('checked')); 
    ... 
} 

而且我知道我不应该props得到checked PARAM但它仅仅是暂时的。

我有什么问题是:当我更新checked param在父母它不更新状态,因为getInitialState不刷新后(是的,我知道它应该是这样)。

我的问题是:我可以以某种方式更新子组件的状态吗?或者它是更好的方式来实现这一点。

回答

2

我的做法是,你应该有结构像这样在父母的渲染:

<ParentView> 
{ this.props.rows.map(function(row) { 
    <ChildRow props={row.props} /> 
    }).bind(this) 
} 
</ParentView> 

,然后row.props你当前行项目是否被选中与否的信息。当父级复选框被切换时,您将使用状态填充所有row.props。

儿童,您会收到那些componentWillReceiveProps和你做魔术(例如设置正确的状态)时复选框被触发:

componentWillReceiveProps: function(props) { 
    this.setState({isChecked: props.isChecked}); 
} 

(信息来自阵营的文档:调用this.setState( )这个函数中不会引发额外的渲染

子元素的渲染会是这样的:

<div> 
    <input type='checkbox' checked={this.state.isChecked} /> 
    <label>{this.props.label}</label> 
</div> 
+5

除非您非常小心,否则最终可能会与孩子争夺父母以控制其状态。恕我直言,最好让孩子无国籍,并由道具驱动。父母可以控制所有孩子的选中状态。 – edoloughlin

+0

@edoloughlin谢谢你的评论,它拯救了我的生命。 –

1

您可以通过将所有子元素的选中状态仅存储在父级中来解决此问题。孩子们只根据道具设置他们的检查状态(他们不使用状态),并调用父母提供的回调来改变它。

例如,在孩子:

render: function() { 
    //... not showing other components... 
     <input type="checkbox" 
       value={this.props.value} 
       checked={this.props.checked} 
       onClick={this.props.onClick}> 
} 

家长提供的onClick,这改变了孩子的检查情况在其状态,并将此回,当孩子重新呈现。

在父:

getInitialState: function() { 
    return { 
     allChecked: false, 
     childrenChecked: new Array(NUM_CHILDREN) // initialise this somewhere (from props?) 
    } 
}, 

render: function() { 
    return <div> 
       <input type="checkbox" checked={this.state.allChecked}> 
       {children.map(function(child, i) { 
        return <Child checked={this.state.childrenChecked[i]} 
           onClick={function(index) { 
            return function() { 
             // update this.state.allChecked and this.state.childrenChecked[index] 
            }.bind(this) 
           }.bind(this)(i)} 
          /> 
       }).bind(this)} 
      </div>; 
} 

- 不检查错别字等

+0

这似乎是我最习惯的反应/助焊剂解决方案 –

+0

是的,非常习惯 –

1

请参阅react documentation上提升状态向上。 在您的孩子组件中,您需要使用道具。要更新道具,您需要提供父级的更新功能。