[React] React 클래스형 컴포넌트

옥수수의 코딩이야기·2023년 2월 4일
0

기술

목록 보기
4/5
post-thumbnail

class형 컴포넌트 사용법

기본 문법

import React, { Component } from 'react';

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

Hello.defaultProps = {
  name: '이름없음'
};

export default Hello;

상태관리 방법
: useState가 아닌 setState를 사용함.

import React, { Component } from 'react';

class Counter extends Component {
  state = {
    counter: 0,
    fixed: 1
  };
  handleIncrease = () => {
    this.setState(
      {
        counter: this.state.counter + 1
      },
      () => {
        console.log(this.state.counter);
      }
    );
  };

  handleDecrease = () => {
    this.setState(state => ({
      counter: state.counter - 1
    }));
  };

  render() {
    return (
      <div>
        <h1>{this.state.counter}</h1>
        <button onClick={this.handleIncrease}>+1</button>
        <button onClick={this.handleDecrease}>-1</button>
        <p>고정된 값: {this.state.fixed}</p>
      </div>
    );
  }
}

export default Counter;

만약 함수의 경우 state를 사용한다면 다음과 같이 사용함.
const [<상태 값 저장 변수>, <상태 값 갱신 함수>] = useState(<상태 초기 값>);

constructor의 대해

사용 예시

class Counter extends Component {
  constructor(props) {
    super(props);
    //state의 초깃값 설정
    this.state = {
      number: 0
    };
  }
  render(){
    return ();
  };
}

surper(props)를 반드시 호출해주어야 함. 이 함수가 호출되면 현재 클래스형 컴포넌트가 상속받고 있는 리액트의 Component 클래스가 지닌 생성자 함수를 호출해 줌.
그 후 this.state 값에 초깃값을 설정해 줌.
state 값을 초기화하거나 메서드를 바인딩 할 수 있음.
constructor()를 사용할때 setState를 호출하면 안됨.

참고 사이트
class형 컴포넌트 : https://react.vlpt.us/basic/24-class-component.html
useState 관련 : https://www.daleseo.com/react-hooks-use-state/
constructor 관련 : https://firework-ham.tistory.com/29

profile
프론트엔드 공부중 기억은 블로그가 대신합니다.

0개의 댓글