this.state = {
color: 'red'
};
color로 지정)color key의 값으로 “red” 를 value로 지정import React, { Component } from 'react';
export class State extends Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
handleColor = () => {
this.setState({
color: 'blue'
})
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Class Component | State</h1>
<button onClick={this.handleColor}>Click</button>
</div>
);
}
}
export default State;
1) <h1> 태그 아래에 <button> 요소 추가
2) <button> 요소에서 onClick 이벤트 발생
3) this.handleColor 함수 실행, this는 현재 컴포넌트(State)를 가르킴
4) handleColor 함수 실행 시 setState 함수 실행
5) state의 color 값을 'blue' 로 변경
6) render 함수 호출
7) 바뀐 state 값을 반영하여 <h1> 태그 글자 색상 변경