React 공식 홈페이지 따라하기

React 만들어보기 (6) - 클래스 컴포넌트

vitamin3000 2025. 1. 27. 13:06

 

이번 포스트에서는 클래스 컴포넌트를 만들어보고자 한다.

 

이전 포스트에서 작성했던 Title을 클래스 컴포넌트로 변환한다면 다음과 같이 작성할 수 있다.

class Title extends Component {
    render() {
        return <h1>{props.children}</h1>
    }
}

 

이때 문법으로 Component를 extends 해주어야하고, 반환값을 render로 감싸야함에 주의하라

 

그렇다면 Component도 작성해야 하겠죠?

export class Component {
    constructor(props){
        this.props = props;
    }
}

 

다음은 이전 포스트에서 작섬한 createElement이다.

export function createElement(type, props,...children) {
    props = props || {};

    if(typeof tag === 'function'){
        
        if (children.length > 0){
            return tag({
                ...props,
                children: children.length === 1 ? children[0] : children,
            })
        }
        else {
            return tag(props);
        }

    }else{
        return { tag, props, children}
    }
}

 

이때 조건문으로 tag의 타입이 function인지 검사하는데, 

함수형과 클래스형 모두 function으로 인식하기 때문에 추가적으로 조건문을 추가해야 한다.

 

function makeProps(props, children) {
    return {
            ...props,
            children: children.length === 1 ? children[0] : children,
    }
}

if(tag.prototype instanceof Component){
    const instance = new tag(makeProps(props, children));
    return instance.render()
}

 

이제 기존에 작성한 클래스 컴포넌트도 수정한다

class Title extends Component {
    render() {
        return <h1>{props.children}</h1>
    }
}

위의 코드의 return문을  

reutrn <h1>{ this.props.children }</h1>

그 이유는 render로인해 context에 들어가있기 때문이다.

 

하지만.. 문제가 존재한다

현재 코드는 다음과 같이 작성되어 있다.

const instance = new tag(makeProps(props, children));

 

이것은 매 실행마다 매번 새로운 instance를 생성함을 의미한다.
즉 기존의 정보는 다 날라감

 

따라서 최초의 instance라면 기존과 같이하고, 그 다음부터는 업데이트되도록 해야 한다

조금 더 자세히 설명하자면 클래스 컴포넌트의 instanceDOM에 마운트되어 rendering 되고 난 이후

즉 컴포넌트가 삭제된 이후 다시 redering된다고 하면 instance를 업데이트 하는 형식(render 호출)으로 수정해야 한다.

 

하지만 이 로직을 구현하기 위해서는 instance를 관리하는 코드를 작성해야하기 때문에 우선 컨셉만 이해하자.

 

결론은 !

함수 컴포넌트는 상태를 가질 수 없고 클래스 컴포넌트는 상태를 가질 수 있는 것이다.