daily3) 우아한 테크러닝 React&TypeScript

iamsummer__·2020년 9월 14일
0

우아한 tech

목록 보기
2/8

3회차에는 react를 간단하게 만들어보았습니다.
dom을 직접 다루다보면 복잡도가 매우 올라가게 됩니다.
react에 virtual dom의 원리는 reflow->repaint와 같은 복잡한 연산의 횟수를 줄여주고자 통틀어 1개의 dom을 리턴하는 형태입니다.

📚 virtual dom

virtual dom
html 문자열을 js에서 컨트롤하기 쉬운 객체 구조로 바꾼 형태입니다.
최종적으로 reactDOM.render를 통해 최상위 부모 컴포넌트가 렌더링되는 구조입니다.

최상위에 부모 컴포넌트가 있으며 자식들이 줄줄이 달려있는 형태입니다.
객체의 형태로 {type, props, children} object 구조입니다.

const vdom = {
  type: "ul",
  props: {},
  children: [
    { type: "li", props: { className: "item" }, children: "React" },
    { type: "li", props: { className: "item" }, children: "Redux" },
    { type: "li", props: { className: "item" }, children: "TypeScript" },
  ],
};
function renderElement(node) {
  if (typeof node === "string") {
    return document.createTextNode(node);
  }

  if (node === undefined) return;

  const $el = document.createElement(node.type);

  node.children.map(renderElement).forEach((node) => {
    $el.appendChild(node);
  });

  return $el;
}

export function render(vdom, container) {
  container.appendChild(renderElement(vdom));
}

export function createElement(type, props, ...children) {
  if (typeof type === "function") {
    return type.apply(null, [props, ...children]);
  }
  return { type, props, children };
}

📚 오픈소스 분석하는 방법

github에 초기 release된 코드가 단촐할때 코드를 찾고서 기본 컨셉 파악!

profile
개발하는 프론트엔드개발자

0개의 댓글