改变子组件的父状态React js

时间:2017-03-21 23:24:09

标签: javascript class reactjs

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

数据对象示例

data =

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

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

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

如果我在data[1].value = 1类中更改Children的值,我该如何设置整个data对象的状态?

1 个答案:

答案 0 :(得分:2)

您需要更新父对象中的数据,并让React自己处理子更新。这看起来是一个例子:

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