React/React Core

7.React 클래스형 컴포넌트 완벽 가이드: 상태와 생명주기를 활용한 UI 구성

코딩쉐프 2024. 11. 25. 00:14
728x90

"React 클래스형 컴포넌트 완벽 가이드: 상태와 생명주기를 활용한 UI 구성"


1시간 분량 강의안 (Class Components 기초)

강의 목표

  1. React 클래스형 컴포넌트의 개념과 역할을 이해한다.
  2. 클래스형 컴포넌트를 작성하고 상태(State)와 Props를 사용하는 방법을 학습한다.
  3. 클래스형 컴포넌트에서 생명주기 메서드를 활용하는 방법을 익힌다.

강의 목차


1. 클래스형 컴포넌트란? (10분)

클래스형 컴포넌트의 정의

  • React 클래스형 컴포넌트는 ES6 클래스 문법을 사용하여 작성됩니다.
  • React의 Component를 상속받아 컴포넌트의 **상태(State)**와 생명주기 메서드를 사용할 수 있습니다.

클래스형 컴포넌트의 주요 특징

  1. 상태 관리: 클래스형 컴포넌트는 상태(State)를 관리하는 기능을 내장하고 있습니다.
  2. 생명주기 메서드 제공: 컴포넌트가 생성, 업데이트, 소멸되는 시점을 제어할 수 있는 메서드를 제공합니다.
  3. Props 활용 가능: 부모 컴포넌트에서 데이터를 전달받아 UI를 동적으로 생성합니다.

클래스형 컴포넌트의 기본 구조

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, React!</h1>;
  }
}

export default Greeting;


2. 클래스형 컴포넌트 작성하기 (20분)

1단계: 기본 클래스형 컴포넌트 작성

  • render 메서드에서 UI를 정의합니다.
import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

export default Greeting;

2단계: Props 사용

  • 부모 컴포넌트에서 Props를 전달하여 데이터를 렌더링합니다.
import React from 'react';
import Greeting from './Greeting';

function App() {
  return <Greeting name="My Name Is React" />;
}

export default App;
  • 결과: Hello, My Name is React!

3단계: State 사용

  • state는 컴포넌트의 내부 데이터를 저장합니다.
import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

export default Counter;
  • 버튼 클릭 시 count 값이 증가합니다.

 


3. 클래스형 컴포넌트의 생명주기 메서드 (20분)

생명주기 단계

  1. Mounting (생성):
    • 컴포넌트가 DOM에 추가될 때 호출.
    • 주요 메서드: constructor, render, componentDidMount
  2. Updating (업데이트):
    • Props 또는 State가 변경될 때 호출.
    • 주요 메서드: shouldComponentUpdate, render, componentDidUpdate
  3. Unmounting (소멸):
    • 컴포넌트가 DOM에서 제거될 때 호출.
    • 주요 메서드: componentWillUnmount

생명주기 메서드 예제

  1. componentDidMount:
    • 컴포넌트가 DOM에 추가된 직후 실행됩니다.
    • 예제: 데이터 가져오기
    componentDidMount() {
      console.log("Component mounted!");
    }
  2. shouldComponentUpdate:
    • 업데이트 여부를 결정.
    • 예제: 특정 조건에서만 업데이트
    shouldComponentUpdate(nextProps, nextState) {
      return nextState.count !== this.state.count;
    }
  3. componentDidUpdate:
    • 컴포넌트가 업데이트된 후 실행.
    componentDidUpdate(prevProps, prevState) {
      console.log("Component updated!");
    }
  4. componentWillUnmount:
    • 컴포넌트가 DOM에서 제거되기 직전에 실행.
     
componentWillUnmount() {
  console.log("Component will unmount!");
}

4. 실습 과제 (10분)

실습 과제

  1. 카운터를 만들고, 버튼 클릭 시 카운트가 증가하도록 설정하세요.
  2. 카운트가 10에 도달하면 콘솔에 "최대 카운트 도달" 메시지를 출력하세요.
  3. 컴포넌트가 제거될 때 "컴포넌트 제거 완료" 메시지를 출력하세요.

예제

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 }; // isUnmounting 제거
  }

  componentDidMount() {
    console.log('컴포넌트가 마운트되었습니다.');
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.count === 10) {
      console.log('최대 카운트 도달');
    }
  }

  componentWillUnmount() {
    console.log('컴포넌트 제거 완료'); // 컴포넌트 제거 시 무조건 실행
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button
          onClick={() => {
            if (this.state.count < 10) {
              this.setState({ count: this.state.count + 1 });
            }
          }}
        >
          Increment
        </button>
      </div>
    );
  }
}

export default Counter;
// src/App.js
import React, { useState } from 'react';
import Greeting from './Components/greeting'; // Counter 컴포넌트 가져오기
import Counter from './Components/counter'; // Counter 컴포넌트 가져오기

function App() {
  const [showCounter, setShowCounter] = useState(true);

  const handleRemoveCounter = () => {
    console.log('Counter 제거 버튼 클릭');
    setShowCounter(false); // Counter를 제거
  };

  return (
    <div>
      <h1>React Counter App</h1>
      <button onClick={handleRemoveCounter}>
        {showCounter ? 'Remove Counter' : 'Show Counter'}
      </button>
      {showCounter && <Counter />}
    </div>
  );
}

export default App;

 


5. Q&A 및 정리 (10분)

  • Q&A:
    1. 클래스형 컴포넌트와 함수형 컴포넌트 중 어떤 것을 사용해야 하나요?
    2. 생명주기 메서드의 역할은 무엇인가요?
  • 요약:
    • 클래스형 컴포넌트는 React의 초기 방식으로, State와 생명주기를 활용해 동적인 UI를 구성할 수 있습니다.
    • 함수형 컴포넌트와 비교했을 때 구조가 더 복잡하지만, 생명주기를 명시적으로 관리할 수 있다는 장점이 있습니다.
728x90