본문 바로가기

카테고리 없음

React Components, Elements, and Instances

아래 글을 번역한 글입니다.

 

React Components, Elements, and Instances

Many people get confused by the difference between components, their instances, and elements in React. Why are there three different terms…

medium.com

많은 사람들이 리액트에서 컴포넌트, 그 인스턴스, 엘리먼트의 차이 때문에 혼란스러워합니다. 화면에 그려지는 것을 지칭하는 용어가 세가지나 되는 이유는 무엇일까요?

 

리액트를 처음 사용한다면 클래스 컴포넌트와 인스턴스만 사용해보셨을 것입니다. 예를 들어, 클래스를 생성하여 Button 컴포넌트를 선언할 수 있습니다.프로그램이 실행 중일 때 화면에 이 컴포넌트의 인스턴스가 여러개 표시될 수 있으며, 각 인스턴스에는 고유한 프로퍼티와 로컬 상태가 있습니다. 이것이 전통적인 객체 지향 UI 프로그래밍입니다. 왜 element를 도입할까요?

 

이 전통적인 UI 모델에서는 자식 컴포넌트 인스턴스를 생성하고 소멸하는 것은 사용자의 몫입니다. 만약 폼 컴포넌트가 버튼 컴포넌트를 렌더링하려면 해당 인스턴스를 생성하고 새로운 정보가 있으면 수동으로 최신 상태로 유지해야 합니다. 

 

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);
    }
  }
}

 

이 코드는 의사 코드이지만, 백본과 같은 UI 프레임워크를 사용하여 객체 지향 방식으로 일관되게 작동하는 컴포저블 UI를 작성하려고 할 때 결국에는 이 코드와 거의 비슷합니다.

 

각 컴포넌트는 DOM 노드와 자식 컴포넌트의 인스턴스에 대한 참조를 유지하고 적절한 시점에 생성, 업데이트, 소멸해야 합니다. 코드 라인은 컴포넌트의 상태 수의 제곱만큼 늘어나고 부모 컴포넌트는 자식 컴포넌트 인스턴스에 직접 엑세스할 수 있으므로 나중에 분리하기가 어렵습니다. 

 

이제 리액트에 대해 이야기해봅시다.