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λ μ΄λ κ² κ°μ²΄ ννλ‘ μ μνλ€. κ·Έλ λ€λ©΄ μ΄λ κ² μ»΄ν¬λνΈμ stateλ₯Ό μ€μ νκ³ λ¬΄μμ ν μ μλ κ±ΈκΉμ? μ μ΄λ° μ»΄ν¬λνΈμ μνκ°μ΄ νμν κ±ΈκΉμ? λ€μμΌλ‘ μ€μ 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 μμμ μΈλΌμΈ μ€νμΌμ μ μ©νκΈ° μν΄, κ·Έ μ€μμλ κΈμμμ μ€μ ν΄μ£ΌκΈ° μν΄ λ€μκ³Ό κ°μ΄ μμ±νλ€.
<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> νκ·Έ κΈμ μμ λ³κ²½