본문으로 바로가기
반응형

https://ko.wikipedia.org

<"리액트를 다루는 기술" 책 참조>


클래스 컴포넌트 예제

import React, { Component } from 'react';

class Example1 extends Component {
    constructor(props) {
        super(props);

        //state의 초깃값 설정
        this.state = {
            number: 0
        };
    };

    render() {
        const { number } = this.state; // state를 조회할 떄는 this.state로 조회
        return (
            <div>
                <h1>{number}</h1>
                <button onClick={() => {
                    this.setState({ number: number + 1 });
                }}
                >
                    + 1
                </button>
            </div>
        )
    }
}

export default Example1;​

 

constructor(props) 사용 이유

Component를 생성할 때 state 값을 초기화하거나 메서드를 바인딩할때 사용

해당 컴포넌트가 마운트 되기 전 호출됨.

 

super(props) 사용 이유

super()는 부모 클래스의(Component) 생성자를 참조함.

super()를 선언 전까지 constructor() 안에 this 키워드를 사용할 수 없음.

 

반응형