REACT lifting state up

Hyein Son·2020년 7월 5일
0

데이터의 변경사항을 여러 컴포넌트에 반영할 때 사용한다. 가장 가까운 부모 컴포넌트에서 state를 관리한다. state를 변화시키는 함수를 자식 컴포넌트에 props로 전달하고, 자식컴포넌트에서 그 함수를 실행해 변화하는 state를 다른 자식 컴포넌트에 props로 전달하는 형태로 사용한다.

index.js

class index extends Component {
  state = {
    num: 0
  };

  clickHandler = (n)=>{
    this.setState({
      num : this.state.num + n
    })
  }  
  render() {
    return (
      <div className="lifting-state-up-parent">
        <div className="top">나는 부모</div>
        <div className="bottom">
          <FirstChild click = {this.clickHandler}/>
          <SecondChild num={this.state.num}/>
        </div>
      </div>
    );
  }
}

export default index;

clickHandler함수를 <FirstChild />click이라는 이름으로 props로 전달한다.


FirstChild.js

class FirstChild extends Component {
  render() {
    return (
      <div className="first-child">
        FirstChild
        <div>여기서 누르는 버튼이</div>
        <div className="body">
          <button onClick={()=>this.props.click(-1)}>-</button>
          <button onClick={()=>this.props.click(1)}>+</button>
        </div>
      </div>
    );
  }
}

export default FirstChild;

인자를 1과 -1로 함수를 호출해 부모 컴포넌트 <index />에서 state를 변화시킨다.


SecondChild.js

class SecondChild extends Component {
  render() {
    return (
      <div className="second-child">
        SecondChild
        <div>여기 내용을 변경해야 할 때</div>
        <div className="body">{this.props.num}</div>
      </div>
    );
  }
}

export default SecondChild;

변화한 state를 다른 자식 컴포넌트 <SecondChild />로 전달해 화면에 보여준다.

0개의 댓글