React Components, Elements, 그리고 Instances

sudyn·2023년 9월 30일

react

목록 보기
3/12

기존 UI모델 - OOP의 문제점


  • 부모와 자식 컴포넌트를 분리하기 어려움(의존도 높음)
    • 부모가 자식을 직접적인 참조 가지므로
    • 부모 컴포넌트에서 자식 컴포넌트의 생성과 종료까지 관리해야하므로
  • 관리할 컴포넌트가 늘어나면 컴포넌트 코드의 복잡도 증가
    • 인스턴스가 많아지며 관리할 코드가 많아짐
class Form extends TraditionalObjectOrientedView {
  render() {
    // Read some data passed to the view
    const { isSubmitted, buttonText } = this.attrs;

    if (!isSubmitted && !this.button) {
      // Form is not yet submitted. Create the button!
      this.button = new Button({
        children: buttonText,
        color: 'blue'
      });
      this.el.appendChild(this.button.el);
    }

    if (this.button) {
      // The button is visible. Update its text!
      this.button.attrs.children = buttonText;
      this.button.render();
    }

    if (isSubmitted && this.button) {
      // Form was submitted. Destroy the button!
      this.el.removeChild(this.button.el);
      this.button.destroy();
    }

    if (isSubmitted && !this.message) {
      // Form was submitted. Show the success message!
      this.message = new Message({ text: 'Success!' });
      this.el.appendChild(this.message.el);
    }
  }
}

이를 리액트는 element 개념을 도입해 해결해줌

Element


  • 실제 화면에 나타내는 UI요소
  • DOM 트리에 전달할 정보(type, props)를 가지고 있는 자바스크립트 일반 객체
  • type의 종류에 따라 DOM 엘리먼트, 컴포넌트 엘리먼트로 나뉨
  • 영속성을 가지지 않는 불변객체

element를 생성하는 방법


1) React.createElement() 함수

하나하나 타이핑해야하고 직관적이지 못해 가독성이 떨어짐 → JSX로 해결

React.createElement(
  'div',
  { className: 'name' },
  'React'
)

2) JSX 문법 사용하기

<div className='name'>React</div>

DOM Element

해당 태그를 가진 DOM 노드를 표현하며 React 가 실제로 화면에 렌더링 하는 대상

  • type : 해당컴포넌트가 어떤 HTML 태그인지 명시(string 문자열)
  • props : 해당 HTML 태그의 속성 명시
<div className='name'>React</div>

// element
{
  type: '**div**',
  props: {
    className: 'name',
    children: 'React'
  }
}

Component Element

props를 받아와 React Element를 반환하는 클래스 혹은 함수
애플리케이션에서 UI를 추상화, 모듈화

  • type : 함수/클래스형 컴포넌트
  • component Elements에 어떤 정보를 전달해야 렌더링 될지 결정하는 속성

type이 string이 될때까지 계속(DOM node)를 찾을때까지 반복함

ReactDOM.render({
  type: Form,
  props: {
    isSubmitted: false,
    buttonText: 'OK!'
  }
}, document.getElementById('root'));

{
  type: SignUpForm
  props: {
    isSubmitted: false,
    buttonText: 'OK!'
  }
}


{
  type: Button,
  props: {
    children: 'OK!',
    color: 'blue'
  }
}

type: 'button',
  props: {
    className: 'button button-blue',
    children: {
      type: 'b',
      props: {
        children: 'OK!'
      }
    }
  }
}

엘리먼트들이 모여서 트리로 구성되고 가상 DOM에 대한 표현을 의미


Instance

  • 클래스형 컴포넌트에서 생성된 실제 객체(함수형 존재x)
  • this로 참조하는 것
  • 리액트 자체가 인스턴스를 생성하고 관리해줌
  • 인스턴스를 통해 컴포넌트의 state나 render()에 접근할 수 있음
const myComponentInstance = new MyComponent();

Component

  • 리액트 앱을 구성하는 최소한의 단위
  • UI를 재사용 가능한 개별적인 여러 조각으로 나눈 것
  • props를 입력으로 받은 후, 화면에 어떻게 표시되는지 element tree를 반환하는 함수 혹은 클래스
  • 함수/클래스 컴포넌트가 있음

참고

https://hkc7180.medium.com/react-components-elements-and-instances-번역글-b5744930846b

https://seokzin.tistory.com/entry/React-엘리먼트와-컴포넌트-Element-Component-JSX

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

0개의 댓글