β
State & Event
π State κ°μ²΄
π Classν μ»΄ν¬λνΈμμ state κ°μ²΄, μ¦ ν΄λΉ μ»΄ν¬λνΈμ μνλ₯Ό μ΄λ»κ² μ μ νλκ°?
import React from 'react'; class Practice extends React.Component { constructor() { // constructor() { } ν¨μ μ μΈ(μμΉ μ μνκΈ°) super(); this.state = { // μ»΄ν¬λνΈμ μ΄κΈ°κ° μ€μ , μ»΄ν¬λνΈμ stateλ κ°μ²΄μ΄λ€. color: 'red' // κ°μ²΄ μμ 'ν€:κ°' ννμ μ΄κΈ°κ°μ΄ λ΄κ²¨μλ€ }; } render() { // μ΄ν ν΄λμ€ν μ»΄ν¬λνΈ μμ νμμμ(render ν¨μ, returnλ¬Έ μμ JSX μμ) return ( <div> <h1> Hello! </h1> <main> <p style={{ color: this.state.color }}>I like blue </p> // pνκ·Έ κ°μ²΄(state)μ νΉμ key(color) κ°μ μ κ·Όνμ¬ κ·Έ κ°μ color μμ±μ valueλ‘ μ§μ (μ€κ΄νΈ 2λ² κ²ΉμΉκΈ° μ μ) // this.state.colorλ‘ μ μνμ¬ constructor ν¨μμ ν€κ°μ μ μ©(ν΄λΉ μμμ κΈμ μμ μ»΄ν¬λνΈμμ μ€μ ν state κ°μΌλ‘ νκ³ μΆμ κ²½μ°) </main> </div> ); } } export default State;β
stateλ₯Ό μ€μ ν λλconstructorΒ ν¨μλ₯Ό μμ± ν κ·Έ μμ μ€μ .
βconstructorν¨μλ μ»΄ν¬λνΈ μ μΈλ¬Έ(class State extends Component)κ³Όrenderν¨μ μ¬μ΄μ μμ±. μμΉ μ μ!!
β‘constructor ν¨μμμ»΄ν¬λνΈκ° μ μ°κ²°λμλμ§ νμΈνλ €λ©΄render()μμμ console.log μ°μ΄λ³΄κΈ°
βconstructorλ©μλ μμλΒsuper()λ₯Ό νΈμΆ.
βthis.stateΒ κ°μ μ»΄ν¬λνΈμ μ΄κΈ° μνκ°μ μ€μ .π§
stateμμ μνκ°μ μ€μ νλ μ΄μ λ, μ»΄ν¬λνΈ μμ μμμμ κ·Έ μνκ°μ λ°μν΄μ λ°μ΄ν°κ° λ°λ λλ§λ€ ν¨μ¨μ μΌλ‘ νλ©΄(UI)μ λνλ΄κΈ° μν¨ μ΄λ€.
β
Event & setState
π State κ°μ²΄
stateκ° λ³κ²½λλ©΄, μ»΄ν¬λνΈλ 리λ λλ§λλ€.π setStateλ₯Ό ν΅ν΄ Event μ μ©νλ λ°©λ²
import React from 'react'; class Practice extends React.Component { constructor() { // constructor() { } ν¨μ λ΄ μ»΄ν¬λνΈμ μ΄κΈ°κ° μ€μ super(); this.state = { color: 'red' }; } handleColor = () => { // this.handleColor, μ¦ νμ¬ μ»΄ν¬λνΈ(State)μ handleColor ν¨μ μ€ν this.setState({ color: 'blue' }) } render() { return ( <div> <h1> Hello! </h1> <main> <p style={{ color: this.state.color }}>I like blue </p> // button μμ μΆκ° λ° onClick μ΄λ²€νΈ μ μ© <button onClick={this.handleColor> Click </button> // handleColor ν¨μ μ€ν μ setState ν¨μ μ€ν β‘ stateμ color κ°μ 'blue' λ‘ λ³κ²½ </main> </div> ); } } export default State;β μ½λ μ€ν μμ
πΈ JSX λ΄<button>μμμμ onClick μ΄λ²€νΈ λ°μ
πΈthis.handleColor(=νμ¬ μ»΄ν¬λνΈμΈstateμ handlerColor ν¨μ) μ€ν
πΈhandleColorν¨μ μ€ν μ,setStateν¨μ μ€ν β‘stateμ colorκ°μ blueλ‘ λ³κ²½
πΈrenderν¨μ νΈμΆπ§ JSX ν¨μλ₯Ό μ½μ΄λ΄λ € κ°λ©΄μ μ§μ ν¨μλ₯Ό λ§μ£ΌμΉλ©΄, ν΄λΉ ν¨μλ₯Ό μ°Ύμ μ¬λΌκ°μ μ€ν. μ¦
re-renderλλ€.
(κ°μ΄ redμμ λ(<p>νκ·Έ) render, κ°μ΄ blueμμ λ(<button>νκ·Έ) re-render)