React State
State
- 컴포넌트 내부에 있는 상태값(객체 형태)
- 데이터 변경 가능
클래스형 컴포넌트에서 state 정의
import React from 'react'
class State extends React.Component{
constructor(){
super();
this. state = {
color: 'red',
};
}
render(){
return(
<div>
<h1 style={{ color: this.state.color }}>aaa</h1>
</div>
);
}
}
- state가 객체 형태이기 때문의 사용 예시와 같이 .으로 접근할 수 있다(this.state.color).
--> this=현재 컴포넌트, state=state 객체, color= state 객체의 키값
import React from 'react'
class State extends React.Component{
constructor(){
this.state = {
color: 'red',
};
}
handleColor = () =>{
this.setState({
color: 'blue',
})
}
render(){
return(
<button onClick={this.handleColor}>Click</button>
)
}
}
- setState을 통해 state값 변경 예시