본문 바로가기
react

[react] 클래스형 컴포넌트

by dev__log 2024. 7. 11.

함수형 컴포넌트는 많이 사용해 봤는데 클래스형 컴포넌트는 사용해 본 적이 없어서 기록하게 되었다.

 

먼저, 클래스형 컴포넌트는 react의 Component 클래스를 상속받아야 하기 때문에 import 해준다.

또한, render 메서드를 포함해야 한다. 

 

아래의 코드는 color와 text 속성을 props로 내려준다.

App.tsx

import {Component} from 'react'
import ClassComponent from './ClassComponent'

export default class App extends Component {
  render() {
    return (
      <div>
        <ClassComponent color="red" text="빨강~" />
        <ClassComponent color="green" text="초록~" />
        <ClassComponent color="pink" text="분홍~" />
      </div>
    )
  }
}

 

color 속성은 style에 적용하여 글자 색을 변경하도록 하였고, text 속성은 렌더링 될 글자를 지정하였다.

 

 

위 속성을 내려받을 컴포넌트는 typescript일 경우 아래와 같이 props에 대한 타입을 지정해야 한다.

ClassComponent.tsx

import {Component} from 'react'

//props 타입 지정
type ClassCompnentProps = {
  color: string
  text: string
}

export default class ClassComponent extends Component<ClassCompnentProps> {
  render() {
    //기본
    // const color = this.props.color
    // const text = this.props.text

    //구조분해 할당
    const {color, text} = this.props

    return (
      <ul>
        <li>
          <p style={{color: color, backgroundColor: 'yellow'}}>{text}</p>
        </li>
      </ul>
    )
  }
}

 

 

결과

'react' 카테고리의 다른 글

[react] useCallback  (2) 2024.07.17
[react] PropsWithChildren  (0) 2024.07.11
react-query useQuery / useMutation  (0) 2024.02.19
axios  (0) 2024.02.16
react-router outlet  (0) 2024.02.07