📍state
리액트에서 state란, 컴포넌트 내부에서 바뀔 수 있는 값을 의미한다.
props는 컴포넌트가 사용되는 과정에서 부모 컴포넌트가 설정하는 값으로 컴포넌트 자신은 해당 props를 읽기 전용으로만 사용할 수 있음. props를 바꾸려면 부모 컴포넌트에서 바꿔야함.
리액트에는 두 가지 종류의 state가 있음.
클래스형 컴포넌트가 지니고 있는 state
클래스형 컴포넌트에서는 this.state를 통해 상태를 관리하고, setState 메서드를 통해 상태를 업데이트함.
함수형 컴포넌트에서 useState라는 함수를 통해 사용하는 state
함수형 컴포넌트에서는 useState 훅을 사용해 상태를 정의하고 업데이트함.
import React, { Component } from 'react';
class Counter extends Component {
// 컴포넌트에 state를 설정할 때 => constructor 메서드 작성
constructor(props) {
super(props);
// state의 초깃값 설정하기
this.state = {
number: 0
};
}
render() {
const { number } = this.state; // state를 조회할 때는 this.state로 조회
return (
<div>
<h1>{number}</h1>
<button
// (이벤트 설정)
// onClick을 통해 버튼이 클릭되었을 때 호출할 함수를 지정
// 이벤트로 설정할 함수를 넣어 줄 때는 화살표 함수 문법을 사용
onClick={() => {
// this.setState를 사용해 state에 새로운 값을 넣을 수 있음(state 값을 바꿀 수 있게 해줌!)
this.setState({ number: number + 1 });
}}
>
+1
</button>
</div>
);
}
}
export default Counter;
컴포넌트의 생성자 메서드

import React from 'react';
// import MyComponent from './features/3_Component/MyComponent';
import Counter from './features/3_Component/Counter';
const App = () => {
return <Counter />;
};
export default App;

