본문 바로가기
to be 개발자

리액트 공부 - LifeCycleSample.js / handleRandomizeColor / 렌더링 사이클 확인 예제 (리액트를 다루는 기술 책 참고)

by 아셀acell 2020. 12. 25.
반응형

LifeCycleSample.js 

 

import React, { Component } from 'react';

 

class LifeCycleSample extends Component {

    state = {

        number: 0,

        color: null,

    }

    myRef = null;

    constructor(props) {

        super(props);

        console.log('constructor');

    }

    static getDerivedStateFromProps(nextProps, prevState) {

        if(nextProps.color !== prevState.color){

            return { color: nextProps.color };

        }

        return null;

    }

    componentDidMount(){

        console.log('componentDidMount');

    }

    shouldComponentUpdate(nextProps, nextState) {

        console.log('shouldComponentUpdate', nextProps, nextState);

        return nextState.number % 10 !== 4 //숫자 마지막자리 4면 리렌더링 안함 

    }

    componentWillUnmount(){

        console.log('componentWillUnmount');

    }

    handleClick = () => {

        this.setState({

            number: this.state.number + 1

        });

    }

    getSnapshotBeforeUpdate(prevProps, prevState){

        console.log('getSnapShotBeforeUpdate');

        if(prevProps.color !== this.props.color){

            return this.myRef.style.color;

        }

        return null;

    }

    componentDidUpdate(prevProps, prevState, snapshot) {

        console.log('componentDidUpdate', prevProps, prevState);

        if(snapshot){

            console.log('업데이트 되기 직전 색상: ', snapshot);

        }

    }

 

    render() {

        console.log('render');

        const style = {

            color: this.props.color

        }

        return (

            <div>

                <h1 style={style} ref={ref => this.myRef=ref}>

                    {this.state.number}

                </h1>

                <p>color: {this.state.color}</p>

                <button onClick={this.handleClick}>

                    더하기 

                </button>

 

                

            </div>

        );

    }

}

 

export default LifeCycleSample;

 

 

App.js

 

import React, { Component } from 'react';

import Mymemo from './Mymemo';

import './App.css';

import LifeCycleSample from './LifeCycleSample';

//랜덤 색상 생성 

function getRandomColor(){

  return '#' + Math.floor(Math.random() * 16777215).toString(16);

  //16777215를 hex로 표현하면 ffffff가 되므로 000000 ~ ffffff 값 반환 

}

 

class App extends Component {

  state ={

    color: '#000000'

  }

 

  handleClick = () => {

    this.setState({

      color: getRandomColor()

    });

  }

  render() {

    return(

      <div>

        <button onClick={this.handleClick}>랜덤 색상</button>

        <LifeCycleSample color={this.state.color}/>

      </div>

    );

  }

}

export default App;

 

 

버튼 렌더링 / 클릭 할때마다 handleRandomizeColor 메서드 호출되게 이벤트 설정 

불러온 LifeCycleSample 컴포넌트에 color 값 props로 설정

 

728x90
반응형
LIST

댓글