함수형 컴포넌트는 리액트 0.14 버전에서 소개되어 16.8 버전에서 훅이 소개되기 전까지는 단순한 무상태 함수형 컴포넌트로만 쓸 수 있어 지금처럼 인기를 끌지는 못했다. 함수형 컴포넌트 훅이 등장한 이후 함수형 컴포넌트에서 상태나 생명주기 메서드를 흉내낼 수 있게 되자 보일러 플레이트가 복잡한 클래스형 컴포넌트에서 함수형 컴포넌트를 더 많이 쓰게 되었다.
import React from 'reate'
class SampleComponent extends React.Component {
render() {
return <h2>Sample Component</h2>
}
}
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>
)
}
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)
}
<button onClick={() => this.handleclick()}>증가</button>