state를 사용한 간단한 실습을 해보겠습니다.
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
// state의 초깃값 설정하기
this.state = {
number: 0,
fixedNumber: 0
// state를 조회할 때는 this.state로 조회합니다.
};
}
render() {
const { number, fixedNumber } = this.state;
return (
<div>
<h1>{number}</h1>
<button onClick={() => {this.setState({number: number +1})}}>
{/* onClick을 통해 버튼이 클릭되었을 때 호출할 함수를 만듭니다. */}
{/* this.setState를 통하여 state에 새로운 값을 부여할 수 있습니다. */}
+1버튼
</button>
</div>
);
}
}
export default Counter;
클래스형 컴포넌트에서 constructor를 작성할 때에는
반드시 super(props)를 호출 해 주어야 합니다.
리액트에서 Component는 모든 클래스형 컴포넌트가 상속받는 기본 클래스입니다.
이 클래스는 컴포넌트 생성과 관련된 기본적인 기능들이 구현되어 있으며
그러한 기능들은 super(props)를 호출하여 사용할 수 있습니다.
⇒ 즉, 컴포넌트의 기능을 사용하기 위해(이경우엔 state를 생성하기 위해)
⇒ constructor(생성자)의 super(props)를 먼저 호출해줍니다.
버튼을 누를때마다 number의 state값이 변경되어 +1씩 되는것을 볼 수 있습니다.