리액트 this 클라스컴포넌트

서울IT코드정리 /kyChoi·2021년 11월 20일
0

리랙트

목록 보기
17/18
import React, { Component } from 'react'

export default class ClassComponent extends Component {
    constructor(props){
        super(props);
        console.log("constructor");
            this.state = {date : new Date()};
            this.handleClick = this.handleClick.bind(this);
    }
    componentDidMount(){
        console.log("componentDidMount");
        this.timerID= setInterval(()=>this.tick(),1000);
    }
    componentDidUpdate(){
      //  console.log("componentDidUpdate");

    }
    componentWillUnmount(){
        console.log("componentWillUnmount");
        clearInterval(this.timerID);
    }
    tick(){
      //  console.log("tick");
        this.setState({date: new Date()});
    }
    handleClick(){
        alert(this.state.date);
    }
    render() {
        //console.log("render");
        return (
            <div>
                <h1 onClick={this.handleClick}>Hello, world !</h1>
                <h2>{this.state.date.toLocaleTimeString()}</h2>
            </div>
        )
    }
}

클라스 내에서 메소드 호출은 마치 갓 태어난 새끼 마냥 부모가 누군지 몰라서 this (얘가) 니 부모다 라고 말해줘야 한다.(데이터 바인딩)
this.handleClik = this.handleClick.bind(this)
근데 귀찮으니 화살표 함수로 handleCLick =>{ alert(this.state.date)} 로 한다.

profile
건물주가 되는 그날까지

0개의 댓글