크게 import
, class
, export
3가지로 나눠지고, state를 적용해 주려면 render
함수 위에 constructor
함수를 작성하고, super()
을 호출하고, this.state
를 불러야 한다.
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;
state 에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영해서 데이터가 바뀔 때마다 효율적으로 화면(UI)에 나타내기 위해서다.
<h1 style = {{ color: this.state.colr }}>Class Component | State</h1>
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;