방법 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
'React' 카테고리의 다른 글
[리액트] 클래스형 컴포넌트 라이프사이클 메서드 componentDidMount 예제 (0) | 2022.08.09 |
---|---|
[리액트] 라이프사이클 useEffect와 componentDidMount, componentDidUpdate, componentWillUnmount 비교하기 (0) | 2022.08.09 |
[리액트] useEffect 훅을 사용해서 데이터 로딩 후에 실행하고 싶은 로직 구현하기 (0) | 2022.08.05 |
[리액트] 라이프사이클이란? 함수형 컴포넌트에서 사용하는 라이프사이클 Hooks 정리 (0) | 2022.08.05 |
[리액트] 라이프사이클이란? 클래스 컴포넌트에서 사용하는 라이프사이클 메서드 정리 (0) | 2022.08.05 |
댓글