Class component | state
state에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영해서 데이터가 바뀔때 마다 효율적으로 화면(UI)에 나타내기 위함입니다.
import React, { Component } from 'react';
export class State extends Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
render() {
return (
<div>
<h1 style={{ color: this.state.color }}>Class Component | State</h1>
</div>
);
}
}
export default State;
- return 문 안에 h1 타이틀 요소가 있습니다. 해당 요소의 글자 색을 컴포넌트에서 설정한 state 값으로 하고 싶은 경우, 다음의 순서대로 state 값을 특정 요소에서 반영할 수 있습니다.
- 우선 JSX 요소에 인라인 스타일을 적용하기 위해, 그 중에서도 글자색을 설정해주기 위해 다음과 같이 작성합니다.

- doot notation을 사용하여 state의 특정 key 값에 접근하여 그 값을 color 속성의 value로 지정해주었습니다.

## 1-3 Event & setState
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;
- h1태그 아래에 button 요소를 추가해주었고 다음과같이 코드가 실행됩니다.
1. button 요소에서 onClick 이벤트 발생
2. this.handleColor, 즉 현재 컴포넌트(State)의 handleColor 함수 실행
3. handleColor 함수 실행 시 setState 함수 실행 -state 의 color 값을 'blue'로 변경
4. render 함수 호출
5. 바뀐 state 값을 반영하여 h1 태그 글자 색상 변경
위와 같이 조건이 두개 중 하나로 선택되는 경우에 data type을 true or false로 쉽게 정의하는 방법도 있다.
import React, { Component } from 'react';
export class State extends Component {
constructor() {
super();
this.state = {
color : ture
};
}
handleColor = () => {
this.setState({
color: !this.state.titleColor
});
};
render() {
return (
<div>
<h1 style={{ color: this.state.color ? 'blue' : 'pink' }}>Class Component | State</h1>
<button onClick={this.handleColor}>Click</button>
</div>
);
}
}
export default State;
위에서 사용되는 '?' 는 삼항 조건 연산자이다. 이는 보통 if문을 대체하면서 쓰이는데, condition이 true이면, 연산자는 expr1의 값을 반환하며, 반대의 경우 expr2를 반환한다.