반응형
SMALL
- props와 달리 자기 자신이 가지고 있다.
(cf. props는 부모 컴포넌트가 자식 컴포넌트에게 주는 값 / 읽기전용)
- 컴포넌트 내부에서 선언하며 내부에서 값을 변경할 수 있다.
- 변경할 때는 항상 setState 함수를 사용한다.
import React,{Component} from 'react';
class Counter extends Component{
// state는 꼭 객체여야한다.
state = {
number : 0
}
handleIncrease=()=>{
// 업데이트 할 때는 항상 setState 함수 사용!
this.setState({
number: this.state.number+1
})
}
handleDecrease=()=>{
this.setState({
number: this.state.number-1
})
}
render(){
return (
<div>
<h1>Counter</h1>
<div>값: {this.state.number} </div>
<button onClick={this.handleIncrease}>+</button>
<button onClick={this.handleDecrease}>-</button>
</div>
)
}
}
export default Counter;
만약 화살표 함수가 아닌 일반함수를 사용하면 this가 뭔지 모르기 때문에 state 아랫부분에 constructor를 이용해서 this가 무엇인지 명시해주어야한다.
constructor(props){
super(props);
this.handleIncrease = this.handleIncrease.bind(this);
this.handleDecrease = this.handleDecrease.bind(this);
}
반응형
LIST
'React' 카테고리의 다른 글
[React] LifeCycle API 사용 예제 (0) | 2020.10.05 |
---|---|
[React] LifeCycle API 설명 (0) | 2020.10.04 |
[React] 함수형 컴포넌트 (+비구조화 할당) (0) | 2020.10.04 |
[React] props 디폴트 값 설정하기 (0) | 2020.10.04 |
React 시작하기 (0) | 2020.10.04 |
댓글