Thief of Wealth
article thumbnail

이제 리액트의 핵심기능 중 하나인 createElement를 구현해보자.

 

코드를 먼저보자!

 

const TinyReact = (() => {
  const createElement = (type, attrs = {}, ...children) => {
    // 최하위 자식부터 돌 수 있도록 child를 재귀로 구현해야함.

    const childElements = [];
    children.forEach((child) => {
      if (child !== null && child instanceof Object) {
        childElements.push(child);
      } else {
        if (typeof child !== "boolean") {
          childElements.push(createElement("text", { textContent: child }));
        }
      }
    });

    return {
      type,
      children: childElements,
      props: Object.assign({ children: childElements }, attrs),
    };
  };

  return {
    createElement,
  };
})();

 

기본적으로 createElement는 재귀적으로 호출하여, 가장 하위의 자식이 먼저 호출되도록 한다.

그리고 null이 아니고 원시타입이 아니면 child객체 그대로 childElement로 취급하며,

그 외의 경우는 boolean값이 아니면 text 값이라고 판단하고 text element를 element로 넣어준다.

 

index.js를 바꾸지 않았다면 아래와 같은 결과값이 보여질 것이다.

 

커밋: github.com/zereight/Tiny-React/commit/fbe18e66f748594c3e19031168e8f5bbd51eb444

profile on loading

Loading...