Javascript 从父 React 刷新子状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29848967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:06:49  来源:igfitidea点击:

Refreshing children state from parent React

javascriptreactjsrefluxjs

提问by Tomasz Kasperek

I have a table with some data and each element in the table is a React class component. It looks like this:

我有一个包含一些数据的表格,表格中的每个元素都是一个 React 类组件。它看起来像这样:

Table

桌子

All i want is to have one checkbox for "check all" feature (top left checkbox). The thing is I don't know how to solve that because of propsand state.

我想要的只是有一个“全选”功能的复选框(左上角的复选框)。问题是我不知道如何解决这个问题,因为propsstate

I have code like that in single element component:

我在单元素组件中有这样的代码:

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

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

And I know I shouldn't get checkedparam from propsbut it is just temporary.

而且我知道我不应该从中获取checked参数,props但这只是暂时的。

What I have problem with is: When I update checkedparam in parent it doesn't update state, because getInitialStateisn't called after refresh (yep, i know it should be like that).

我的问题是:当我checked在父级中更新参数时,它不会更新状态,因为getInitialState刷新后没有调用(是的,我知道它应该是这样)。

My question is: can I somehow update state of child component?Or it is better way to achieve that.

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

回答by Samuli Hakoniemi

My approach is that you should have structure something like this in parent's render:

我的方法是你应该在父级的渲染中有这样的结构:

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

And then on row.propsyou have the information whether current row item is checked or not. When parent checkbox is toggled, you populate all the row.props with the status.

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

On child, you will receive those with componentWillReceivePropsand you do the magic (e.g. set the correct state) when checkbox is toggled:

在孩子上,componentWillReceiveProps当复选框被切换时,您将收到那些并执行魔术(例如设置正确的状态):

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

(Info from the React's docs: Calling this.setState() within this function will not trigger an additional render.)

(来自 React 文档的信息:在此函数中调用 this.setState() 不会触发额外的渲染。

Child element's render would be something like:

子元素的渲染类似于:

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

回答by edoloughlin

You can solve this by storing the checked state of all child elements in the parent only. The children set their checked status based on props only (they don't use state for this) and call a callback supplied by the parent to change this.

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

E.g., in the child:

例如,在孩子中:

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

The parent supplies the onClick, which changes the checked status of the child in its state and passes this back to the child when it re-renders.

父级提供onClick,这会更改子级在其状态下的检查状态,并在重新渲染时将其传回给子级。

In the parent:

在父级中:

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>;
}

-- not checked for typos etc.

- 没有检查错别字等。

回答by Duray Akar

Please see the react documentationon Lifting State Up. In your child component, you need to use the props. To update the prop, you need to provide an update function from the parent.

请参阅有关提升状态的反应文档。在您的子组件中,您需要使用道具。要更新道具,您需要从父级提供更新功能。