본문 바로가기
React

[리액트] 클래스형 컴포넌트에서 일반함수, 화살표 함수 사용하는 방법

by 메이플 🍁 2022. 8. 9.

방법 1) 화살표 함수 사용

클래스에서 화살표 함수를 사용하는 방식은 정식 클래스 컴포넌트 문법은 아니다

다만 일반 함수를 사용할 경우 bind를 해줘야하는 번거로움이 있기 때문에 자주 사용한다

import React, { Component } from 'react'

class Count extends Component {
  state = {
    number: 0
  }

  countUp = () => {
    this.setState({
      number: this.state.number + 1
    })
  }

  render() {
    return (
      <>
        <div>{ this.state.number }</div>
        <button onClick={ this.countUp }>+1</button>
      </>
    )
  }
}

export default Count

 

방법 2) 일반 함수 사용

정식 클래스 컴포넌트 문법은 constructor를 사용해 state를 내부에서 등록해주고 함수를 bind 해준다

화살표 함수를 쓰지 않고 일반 함수를 선언한 경우에는 this를 bind해주어야만 사용이 가능하다

import React, { Component } from 'react'

class Count extends Component {
  constructor(props) {
    super(props) // super(props)를 작성해줘야만 this 사용 가능
    this.countUp = this.countUp.bind(this) // this를 bind 해줘야만 해당 countUp 함수 내에서 this 사용이 가능해진다
    this.state = { // state도 내부에서 작성한다
      number: 0
    }
  }

  countUp = () => {
    this.setState({ // 위에서 bind를 해주지 않았다면 undefined가 표시된다
      number: this.state.number + 1
    })
  }

  render() {
    return (
      <>
        <div>{ this.state.number }</div>
        <button onClick={ this.countUp }>+1</button>
      </>
    )
  }
}

export default Count

댓글