[React] 4강 클래스 컴포넌트

youngseo·2022년 7월 30일
0

REACT

목록 보기
34/52
post-thumbnail

리액트 컴포넌트

react 의 component 는 함수형으로 작성하는 방식과, 클래스형으로 작성하는 방식이 있습니다.

함수형 예시

import React from 'react';

function Hello({ color, name, number }) {
  return (
    <div style={{ color }}>
      안녕하세요 {name}
    </div>
  );
}

export default Hello;

클래스형 예시

import React, { Component } from 'react';

class Hello extends Component {
  render() {
    const { color, name, number } = this.props;
    return (
      <div style={{ color }}>
        안녕하세요 {name}
      </div>
    );
  }
}

export default Hello;

최근에는 함수형을 쓰는 것이 트렌드이고, 코드 자체도 클래스형을 쓸 때보다 훨씬 짧아지기에 함수형을 권장합니다.

클래스 컴포넌트

그렇다고 클래스 컴포넌트가 사용되지 않는 것이 아닙니다. 리액트 공식문서에도 클래스 컴포넌트를 없애지는 않을 거라고 명시가 되어 있습니다.

컴포넌트의 기본적인 구조

함수형의 경우 function 안에서 return()을 사용했지만 클래스 컴포넌트의 경우 class안에서 render(){}로 한번 감싸서 render(){ return()}을 해줘야 합니다.

1.props

  • 클래스 컴포넌트의 경우 react 가 제공하는 Component 를 상속받습니다.
  • props 를 가져올 때는 그냥 props 가 아니라, this.props 라고 해줘야 합니다.
import React, { Component } from 'react';

class Comp extends Component {

  render() { // render() 를 붙여줘야만 렌더가 됨
    const { name } = this.props;

    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
}

export default Comp;

2. defaltprops

defaultprops 설정은 동일합니다!

import React, { Component } from 'react';

class Comp extends Component {

  render() { // render() 를 붙여줘야만 렌더가 됨
    const { name } = this.props;

    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
}

Comp.defaultProps = {
  name: '기본 이름'
}

export default Comp;

3. state

함수형 컴포넌트에서는 useState를 react에서 가져와 사용을 했다면 클래스 컴포넌트에서는 Component를 가져와 아래 예시처럼 state 라고 해서 생성 및 setState 라고 해서 수정할 수 있씁니다.

import React, { Component } from 'react';

class Comp extends Component {
  state = {  
    num: 0
  }

countUp = () => {
  this.setState({
    num: this.state.num + 1
  });
};

countDown = () => {
  this.setState({
    num: this.state.num - 1
  });
};

render() { // render() 를 붙여줘야만 렌더가 됨
  return (
    <div>
      <h1>{this.state.num}</h1>
      <button onClick={this.countUp}>카운트업!</button>
      <button onClick={this.countDown}>카운트다운!</button>
    </div>
  );
}
}

export default Comp;

※constructor

화살표함수를 쓰지 않고 함수를 선언한 경우에 아래처럼 작성하게 됩니다!
아래가 일반적인 방법이고, 위에서 보신 화살표 함수 문법은 정식 클래스 컴포넌트 문법은 아닙니다.
state 도 constructor 안에 선언되어있음을 기억해주세요!

import React, { Component } from 'react';

class Comp extends Component {
  constructor(props) {
    super(props); // 작성해줘야만 this 사용 가능
    this.countUp = this.countUp.bind(this); // bind 해줘야만 해당 함수 내에서 this 사용 가능
    this.countDown = this.countDown.bind(this);
    this.state = {
      num: 0
    }
  }

  countUp() {
    this.setState({ // 위에 bind 해주는 과정에 없으면 undefined 가 표시되게 됨
      num: this.state.num + 1
    });
  };

  countDown() {
    this.setState({
      num: this.state.num - 1
    });
  };

  render() { // render() 를 붙여줘야만 렌더가 됨
    return (
      <div>
        <h1>{this.state.num}</h1>
        <button onClick={this.countUp}>카운트업!</button>
        <button onClick={this.countDown}>카운트다운!</button>
      </div>
    );
  }
}

export default Comp;

2. 생명주기

  • 렌더이전: constructor 안에 작성한 것이 render 이전에 실행이 됩니다!
  • componentDidMount 가 컴포넌트/요소가 생성될 때, → 빈대괄호 useEffect
  • componentDidUpdate 가 컴포넌트/요소가 업데이트될 때, → 대괄호안에 값이 있는 useEffect
  • componentWillUnmount 가 컴포넌트가 제거될 때 실행되는 부분입니다! → useEffect 안에서 return

componentDidMount

componentDidMount() {
	// 렌더링 시 실행될 코드
}

예제 → num 을 0 으로 생성했음에도, componentDidMount 의 영향으로 화면에는 10 이 보입니다!

import React, { Component } from 'react';

class Comp extends Component {
  constructor(props) {
    super(props); // 작성해줘야만 this 사용 가능
	  this.state = {
	    num: 0
	  }
	}

  componentDidMount() {
    this.setState({
      num: 10
    });
  }

  render() { // render() 를 붙여줘야만 렌더가 됨
    return (
      <div>
        <h1>{this.state.num}</h1>
      </div>
    );
  }
}

export default Comp;

componentDidUpdate

componentDidUpdate(prevProps, prevState) { // 업데이트 되기 이전의 Props, State 값을 받아옴
  // 업데이트 된 값과, 업데이트 되기 이전의 값을 직접 비교해서, 함수를 실행시킴
	// dependency 가 있던 useEffect 와는 차이가 있음에 유의!
  if (this.props.num !== prevProps.num) {
    // num 이 업데이트되었을 때 실행할 코드
  }
}

예제 → state 에 있던 ‘안녕’ 이 num 이 바뀌자 ‘잘가' 로 변경되는 것을 확인할 수 있습니다.

import React, { Component } from 'react';

class Comp extends Component {
  constructor(props) {
    super(props); // 작성해줘야만 this 사용 가능
    this.countUp = this.countUp.bind(this);
	  this.state = {
	    num: 0,
      str: '안녕',
	  }
	}
  
  countUp() {
    this.setState({ // 위에 bind 해주는 과정에 없으면 undefined 가 표시되게 됨
      num: this.state.num + 1
    });
  };

  componentDidUpdate(prevProps, prevState) { // 업데이트 되기 이전의 Props, State 값을 받아옴
    // 업데이트 된 값과, 업데이트 되기 이전의 값을 직접 비교해서, 함수를 실행시킴
    // dependency 가 있던 useEffect 와는 차이가 있음에 유의!
    if (this.state.num !== prevState.num) {
      // num 이 업데이트되었을 때 실행할 코드
      this.setState({
        str: '잘가'
      })
    }
  }
  render() { // render() 를 붙여줘야만 렌더가 됨
    return (
      <div>
        <h1>{this.state.num}</h1>
        <button onClick={this.countUp}>카운트업!</button>
        <h1>{this.state.str}</h1>
      </div>
    );
  }
}

export default Comp;

componentWillUnmount

componentWillUnmount() {
	// 컴포넌트 사라지기 직전에 호출 (실행 중인 함수 종료 등, 메모리 누수 방지)
}

0개의 댓글