Study/React

Child Components Update Their Parents' state

더 멋진 세상을 꿈꾸는 개발자 2020. 6. 1. 21:35

 

지난 레슨에서, 

여러분은 stateful한 부모 컴포넌트에서 stateless한 자녀 컴포넌트로 정보를 전달했다. 

 

이번 레슨에서는, 

당신은 패턴을 좀더 확장할 것이다. 

stateless한 자녀 컴포넌트는 부모 컴포넌트의 state를 업데이트할 수 있다.

 

 

이것이 어떻게 동작하는가 

 

1. 부모 컴포넌트 class는 this.setState()를 호출하는 메소드를 정의한다. 

예를들어, Step1.js의 .handleClick()메소드를 보아라. 

 

//Step1.js

import React from 'react';
import ReactDOM from 'react-dom';
import { ChildClass } from './ChildClass';

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

    this.state = { totalClicks: 0 };
  }

  handleClick() {
    const total = this.state.totalClicks;

    // calling handleClick will 
    // result in a state change:
    this.setState(
      { totalClicks: total + 1 }
    );
  }
}

 

2. 부모 컴포넌트는 새로 정의된 방법을 constructor에 있는 컴포넌트의 현재 인스턴스에 바인딩한다. 

이렇게 하면 자녀 컴포넌트에 메소드를 전달할 때, 부모 컴포넌트 요소가 업데이트 될것이다. 

 

step2.js의 counstructor()메소드의 끝부분을 보아라.

//Step2.js

import React from 'react';
import ReactDOM from 'react-dom';
import { ChildClass } from './ChildClass';

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

    this.state = { totalClicks: 0 };

    this.handleClick = this.handleClick.bind(this);  // 바인드 예시.
  }

  handleClick() {
    const total = this.state.totalClicks;

    // calling handleClick will 
    // result in a state change:
    this.setState(
      { totalClicks: total + 1 }
    );
  }

  // The stateful component class passes down
  // handleClick to a stateless component class:
  render() {
    return (
      <ChildClass onClick={this.handleClick} />
    );
  }
}

 

3. 일단 부모가 업데이트한 메소드와 바인드를 정의하면, 부모는 그 메소드를 자식에게 전달한다.

Step2.js의 28번째 줄 prop을 보아라. 

 

 

4. 자녀는 아래로 전달되는 함수를 받는다. 그리고 이것을 이벤트핸들러로써 사용한다. 

Step3.js를 참조해라.

 

유저가 버튼을 클릭했을때, 버튼 이벤트는 fire할 것이다. 

이것은 부모의 state를 업데이트할 passed-down 함수를 호출할것이다. 

 

import React from 'react';
import ReactDOM from 'react-dom';

export class ChildClass extends React.Component {
  render() {
    return (
      // The stateless component class uses
      // the passed-down handleClick function,
      // accessed here as this.props.onClick,
      // as an event handler:
      <button onClick={this.props.onClick}>
        Click Me!
      </button>
    );
  }
}

 

 

출처: 코드카데미 를 번역하였습니다.