ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • (2) 지금 바로 React 시작하기 - Components
    weniv 2024. 7. 31. 23:49

    1. Components란?

    • 컴포넌트란 markup, style 그리고 유저 인터페이스를 조작하는 logic의 묶음이다.
    • markup(HTML), styles(CSS), logic(JS)로 분리해서 코드를 작성하는 대신에 Component로 애플리케이션을 구축한다.
    • 아래의 이미지를 보고 이해해보자

    Component

    2. 재사용 메커니즘 (Mechanism of reuse)

    • 전통적인 HTML은 markup chunk를 재사용하는 방법을 제공하지 않는다.
    • 재사용을 위해 많은 언어들이 partials을 도입했다.
      • ex) CSS의 class 기준 styles 재사용
      .btn {
        padding: 8px 32px;
        background: blue;
        border: none;
        font-size: 1rem;
      }   
      
      • 해당 CSS를 재사용 하고 싶으면 button에 className을 btn을 붙이기만 하면 된다.
      • JS에서는 재사용을 위해 function 만들고 필요할때 호출하는 방식을 사용한다.
      function shout(sentence) {
        return sentence.toUpperCase() + '!!';
      }
      
      shout("we're off to see the wizard")
      // -> "WE'RE OFF TO SEE THE WIZARD!!"
      
    • React의 components는 이러한 재사용 매커니즘이 주요 목적이다.
    • CSS를 위한 클래스, JS의 함수 그리고 HTML을 Components 단위로 묶어서 재사용 가능한 높은 수준의 UI 라이브러리를 제작할 수 있다.
    • 나중에 살펴볼 Hook 또한 로직 재사용을 위해서이다.

     

    3. 기초 문법 

    • React에서 Components는 함수(functions)로 정의된다.
    • clsss로 정의할 수도 있지만, 권장되지 않는 legacy 대안이다.
    • 일반적으로 React components는 1개 이상의 React elements를 return한다.
    • 아래의 FriendlyGreeting components는 Inline style를 제공하는 p 태그를 생성하는 React elements를 생성한다.
    • 예시를 위해 Inline style를 사용했지만, 더 좋은 방법이 많다. 이후 강의에서 styling 생태계를 살펴볼 예정이다.
    import React from 'react';
    import { createRoot } from 'react-dom/client';
    
    function FriendlyGreeting() {
      return (
        <p
          style={{
            fontSize: '1.25rem',
            textAlign: 'center',
            color: 'sienna',
          }}
        >
          Greetings, weary traveller!
        </p>
      );
    }
    
    const container = document.querySelector('#root');
    const root = createRoot(container);
    root.render(<FriendlyGreeting />);
    

     - <div> <h1>를 rendering하는 대신 components를 rendering 한다.

     

    The Big component rule

    • components 만들때 특정 rule이 있는 것은 아니지만 지켜야하는 철칙이 있다.
    1. Component는 첫글자를 대문자로 만들어야한다.
    • JSX 컴파일러가 HTML 태그를 render할지 component를 render할지 판단의 기준이 되기 때문
    • 대문자로 표기해줘야 컴파일러가 HTML인지 JSX로 만든 컴포넌트인지 명확히 구분할 수 있다.
    // 컴파일 전
    const heading = <h1>Hello!</h1>
    const greeting = <FriendlyGreeting />
    
    // 컴파일 후
    const heading = React.createElement('h1', null, 'Hello!');
    const greeting = React.createElement(FriendlyGreeting, null);
    

     

    반응형
Designed by Tistory.