[ React : 실습 : State, Props, Event (실습) - 2. event 발생을 통한 state 변경 ]

Teasan·2020년 10월 18일
0

React

목록 보기
6/9
post-thumbnail
  1. Event & setState

event로 state 상태 속성 변경해주기

import React, { Component } from 'react';

class State extends React.Component {

    constructor() {
        super();
        this.state = {
            color : ‘red’
        };
    }
    
    handleColor = () => {
        this.setState({
            color : 'grey'
        })
    }

    render() {
        return (
            <div>
                <input 
                    style={{color : this.state.color}} 
                    type="text" value="id">            
                </input>
                <button
                    onClick={this.handleColor}>
                로그인</button>
            </div>
        );
    }
}

export default State;
  1. < button> 요소에서 onClick event 발생
  2. this.handleColor, 즉 현재 component(state)의 handleColor 함수 실행
  3. handleColor 함수 실행 시 setState 함수 실행
  4. state의 color 값을 ‘grey’로 변경
  5. Render 함수 호출
  6. 바뀐 state 값({this.handleColor}) 을 반영하여 < input> 의 style color 변경
  • Button 의 onClick event 발생 전

  • Button 의 onClick event 발생 후

: onClick event를 통해서 {this.handleColor}를 실행하고 handleColor 함수 내에서 setState를 통해 변경한 state 요소 {color : 'grey’}가 본래 state 요소가 적용되었던 input 내의 state가 변경되어 적용되었음을 확인할 수 있다.

profile
일단 공부가 '적성'에 맞는 개발자. 근성있습니다.

0개의 댓글