
import React from 'react';
class State extends React.Component {
constructor() {
super();
this.state = {
color: 'red'
};
}
render() {
return (
<div>
<h1>Class Component | State</h1>
</div>
);
}
}
export default State;
render 함수가 필요하고 화면에 나타내고 싶은 JSX 요소가 return문 안에 들어있습니다.render 함수 위에 constructor 함수를 보도록 하겠습니다.constructor 함수를 작성하여 설정합니다.constructor 함수는 컴포넌트 선언문(class State extends Component)과 render 함수 사이에 작성합니다.super()를 호출합니다.this.state 값에 컴포넌트의 초기 상태값을 설정해 주었습니다. this.state = {
color: 'red'
};
color로 지정하였습니다.color key의 값으로 “red” 를 value로 지정하겠습니다.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 요소에 인라인 스타일을 적용하기 위해, 그 중에서도 글자색을 설정해주기 위해 다음과 같이 작성합니다.
<h1 style={{ color: }}>Class Component | State</h1>
dot notation을 사용하여 객체(state)의 특정 key(color) 값에 접근하여 그 값을 color 속성의 value로 지정해주었습니다.
<h1 style={{ color: this.state.color }}>Class Component | State</h1>
// this : 해당 컴포넌트
// this.state : 해당 컴포넌트의 state 객체
// this.state.color : state 객체의 특정 key(color)값. 즉 "red"
:: 위의 예시에서 볼 수 있듯이, state에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영에서 화면(UI)에 나타내기 위함입니다.
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> 요소를 추가해주었습니다.<button> 요소에서 onClick 이벤트 발생this.handleColor , 즉 현재 컴포넌트(State)의 handleColor 함수 실행handleColor 함수 실행 시 setState 함수 실행 - state의 color 값을 'blue' 로 변경render 함수 호출<h1> 태그 글자 색상 변경