Alter state of parent from a child component React

2019-07-26 09:05发布

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

Example of data object

data =

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

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

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

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

1条回答
虎瘦雄心在
2楼-- · 2019-07-26 09:49

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

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

查看更多
登录 后发表回答