컴포넌트 통신

1. 컴포넌트 간 통신이 필요한 이유

React의 클래스 컴포넌트는 캡슐화 되어 있기 때문에 본인의 상태(state)를 가질 수 있어서 관리가 용이하다. 하지만 컴포넌트가 중첩 되었을 때 개별적으로 상태를 관리하는 특징 때문에 상태를 공유하는 것이 까다롭다.

Ract는 자바 스트립트와 달리 컴포넌트의 상태가 스코프 체인 되지 않는다.

React 프로그래밍에서는 부모 컴포넌트가 상태를 관리하고, 자손 컴포넌트는 부모 컴포넌트와 통신 하여 상태를 공유 처리한다.

2. props ⇌ callback

간단한 컴포넌트 간 통신

import React, { Component } from 'react'
import PropsTypes from 'prop-types'
import Lecture from './Lecture'

class Lecturer extends Component {
  static propTypes = {
    instructor: PropsTypes.array,
  }

  static defaultProps = {
    instructor: [],
  }

  parentComponentMethod = () => {
    console.log('부모 컴포넌트에 콜백 됨')
  }

  render() {
    return (
      <ul className="lecturers">
        {this.props.instructor.map((lecturer) => (
          <Lecture
            key={lecturer.id}
            lecturer={lecturer}
            // onParentCallback이란 이름으로 Lecture(자식) 컴포넌트에 속성을 보냄
            onParentCallback={this.parentComponentMethod}
          >
            <figure className="lecturer-info">
              <img src={lecturer.image} alt="" className="lecturer-photo" />
              <figcaption>
                {lecturer.module} 모듈을 담당 할 {lecturer.name} 강사 Facebook
                바로가기
              </figcaption>
            </figure>
          </Lecture>
        ))}
      </ul>
    )
  }
}

export default Lecturer

2.1 부모 ➡︎ 자식 (메서드 전달)

class Lecturer extends React.Component {
  parentComponentMethood = () => {
    console.log('부모 컴포넌트에 콜백 됨')
  }

  render() {
    return (
      <ul className="lecturers">
        {this.props.instructor.map((lecturer) => (
          <Lecture
            key={lecturer.id}
            lecturer={lecturer}
            onParentCallback={this.parentComponentMethood}
          >
            <figure className="lecturer-info">
              <img src={lecturer.image} alt="" className="lecturer-photo" />
              <figcaption>
                {lecturer.module} 모듈을 담당 할 {lecturer.name} 강사 Facebook
                바로가기
              </figcaption>
            </figure>
          </Lecture>
        ))}
      </ul>
    )
  }
}

2.2 부모 ⬅︎ 자식 (메서드 실행)

const Lecture = ({ lecturer, children, onParentCallback }) => (
  <li className="lecturers">
    <a href={lecturer.facebook} rel="noreferer nopener">
      {children}
    </a>
    <button
      type="button"
      className="button-remove-lecturer"
      // 받아온 onParentCallback을 버튼에 이벤트 바인딩  
      onClick={onParentCallback}
    >
      제거
    </button>
  </li>
)

3. 복잡한 컴포넌트 트리 구조

복잡한 컴포넌트 트리 구조

참고

Last updated

Was this helpful?