클래스형 컴포넌트

변진상·2024년 10월 21일
0

학습 기록

목록 보기
30/31

함수형 컴포넌트는 리액트 0.14 버전에서 소개되어 16.8 버전에서 훅이 소개되기 전까지는 단순한 무상태 함수형 컴포넌트로만 쓸 수 있어 지금처럼 인기를 끌지는 못했다. 함수형 컴포넌트 훅이 등장한 이후 함수형 컴포넌트에서 상태나 생명주기 메서드를 흉내낼 수 있게 되자 보일러 플레이트가 복잡한 클래스형 컴포넌트에서 함수형 컴포넌트를 더 많이 쓰게 되었다.

클래스형 컴포넌트

기본 선언 방법

import React from 'reate'

class SampleComponent extends React.Component {
	
	render() {
		return <h2>Sample Component</h2>
	}
}
  • 기본적으로 class형 컴포넌트를 만들려면 클래스를 선언하고 extends로 만드록 싶은 컴포넌트를 상속받아야한다.
    - 상속 가능한 클래스
    - React.Component
    - React.PureComponent
    - 이 둘의 차이점은 shouldComponentUpdate를 다루는 데 있다(추후에 소개).

props, state, 메서드 정의

import React from 'react'

interface SampleProps {
	required?: boolean
	text: string
}

interface SampleState {
	count: number
	isLimited?: boolean
}

// Props와 State의 타입의 경우 React.Component 컴포넌트에 props, state 순으로 넣어준다.
class SampleComponent extends React.Component<SampleProps, SampleState>{
	private constructor (props: SampleProps) {
		super(props)
		this.state = {
			count: 0,
			isLimited: false
		}
	}

	private handleClick = () => {
		const newValue = this.state.count + 1;
		this.setState({count: newValue, isLimited: newValue >= 10})
		// 기존 count state를 가산하고 count가 10 이상이 될 경우 isLimited가 true
	}

	private render () {
		// this에서 props와 state를 구조분해할당
		const {
			props: {required, text},
			state: {count, isLimited},
		} = this;
	}

	return (
		<h2>
			Sample Component;
		<div>{required? '필수' : '필수아님'}</div>
		<div>문자: {text}</div>
		<div>count: {count}</div>
		<button onClick={this.handelClick} disabled={isLimited}>
			증가
		</button>
		</h2>
	)
}
  • constructor(): 컴포넌트 내부에 이 생성자 함수가 있다면 컴포넌트가 초기화되는 시점에 호출, state를 정의할 수 있다.
import {Component} from 'react'

class SampleComponent extends Component {
  state = {
    count: 1,
  }

render() {
  const {
    state: {count},
  } = this

  return <div>{count}</div>
}
}
  • 이런 문법도 가능한데, ES2022에 추가된 클래스 필드 문법이다. 이 환경을 지원하는 브라우저에서만 코드를 제공하거나 @babel/plugin-proposal-class-properties를 사용해 트랜스파일해야 한다.

  • props: <SampleComponent text = "텍스트"> 이런 형태로 선언해야 한다.

  • state: 클래스형 컴포넌트 내부에서 관리하는 값. 항상 객체여야만 한다. 이 값에 변화가 있을 때마다 리렌더링 발생.

  • 메서드: 렌더링 함수 내부에서 사용하는 함수. 이벤트와 함께 사용.
    - 메서드를 선언하는 3가지 방법
    - constructor에서 this 바인드를 사용하는 방법: 일반적인 함수로 메서드를 만들면 this가 전역 객체에 바인딩 된다.

...
constrctor(props: Prop) {
  super(props)

  this.state = { count: 1, }

  this.handleClick = this.handleClick.bind(this)
}
  • 화살표 함수를 쓰는 방법: 화살표 함수를 쓰는 경우 상위 스코프에 this가 바인딩 되기 때문에 이를 사용할 수 있다.
  • 렌더링 함수 내부에서 새롭게 만들어 전달하는 방법: 이는 렌더링이 일어날 때 마다 새로운 함수를 생성해서 할당하기 때문에 최적화를 수행하기 어려워진다.
<button onClick={() => this.handleclick()}>증가</button>
profile
자신을 개발하는 개발자!

0개의 댓글