<aside> 💡 우리는 함수형 컴포넌트로 수업을 진행하고 있으므로 클래스 컴포넌트 라이프 사이클은 참고로 알아두시면 됩니다. 우리 수업에서는 주로 함수형 컴포넌트를 다루며 이를 Hook Flow라는 컴포넌트 라이프 사이클로 명명합니다. 바로 뒤에서 다뤄보겠습니다.
</aside>
리액트 클래스 컴포넌트는 ES6 클래스를 사용하여 만들어집니다. 이러한 컴포넌트는 상태(state)와 속성(props)을 사용하여 데이터를 관리하고, 라이프 사이클 메서드(lifecycle methods)를 사용하여 컴포넌트의 동작을 제어합니다. 클래스 컴포넌트는 다음과 같은 구조를 가지고 있습니다.
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>지금까지 {this.state.count} 번 클릭하셨습니다.</p>
<button onClick={this.incrementCount}>
클릭하세요.
</button>
</div>
);
}
}
export default MyComponent;
위의 예제에서, MyComponent 클래스는 Component 클래스를 상속받습니다. MyComponent 클래스는 상태 (this.state)를 가지며, constructor 메서드는 컴포넌트가 생성될 때 호출되며, **this.state**를 초기화합니다. incrementCount 메서드를 통해 상태를 변경합니다. 클래스 컴포넌트는 항상 render 메서드를 포함해야하며, render 메서드는 React 요소를 반환하여 컴포넌트를 랜더링합니다.
클래스 컴포넌트의 라이프 사이클입니다. 컴포넌트의 생애주기는 크게 세 가지로 나눌 수 있습니다.
처음 state와 props를 가지고 컴포넌트를 생성합니다.
constructorgetDerivedStateFromPropsrender