从子组件React js更改父级状态 [英] Alter state of parent from a child component React js

查看:91
本文介绍了从子组件React js更改父级状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Parent extends React.Component{
  constructor(props){
     super(props);
     this.state={
        data : props.data
     };  
   }

   render(){
     for(let i=0;i<this.state.data.length;i++){
       let row = this.state.data[i]; 
        //row.value = 0 here 
       outs.push(<Children row={row}/>);
     }      
   }
}

class Children extends React.Component{
  constructor(props){
    super(props);
  }

  render(){
   let row = this.props.row;
       this.changeRowValue(row);
      if(row.value == 1){
          //do something
      }
      ....
  }

  changeRowValue(row){ 
       row.value = 1;
      //how do i set the state of data object here ?
  }
}

数据对象示例

数据 =

[0] => {value : 0,someother : somevalue},

[1] => {value : 0,someother : somevalue},

[2] => {value : 0,someother : somevalue}

data [1] .value = 1 在 Children 类中,如何设置整个 data 对象?

if i change the value of data[1].value = 1 in Children class , how do i set State of whole data object ?

推荐答案

您需要更新父对象中的数据,并让React处理子更新本身。这样的示例如下:

You need to update the data in the parent object and let React handle the child updates itself. An example of how that would look is:

class ParentComponent extends React.Component {
    onChangeValue = (index, newData) => {
        let data = this.state.data;
        data[index] = newData;

        this.setState({ data });
    }

    render() {
        let outs = [];

        for (let i = 0; i < 10; i++) {
            let row = this.state.data[i];

            outs.push(
                <ChildComponent index={ i } row={ row } onChangeValue={ this.onChangeValue }/>
            );
        }

        return <div>{ outs }</div>;
    }
}

class ChildComponent extends React.Component {
    ...

    onChangeValue() {
        const { index, onChangeValue } = this.props;
        this.props.onChangeValue(index, { someNewValue });
    }
}

当您想要更新孩子的某些东西时,您会调用其 onChangeValue 方法,该方法又调用父级的 onChangeValue

when you want to update something in the child, you'd call its onChangeValue method which, in turn, calls the parent's onChangeValue.

这篇关于从子组件React js更改父级状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆