ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [포스코x코딩온] React - Component
    [포스코x코딩온] 웹개발자 풀스택 부트캠프8기 2023. 9. 19. 13:45
    728x90

    https://ko.reactjs.org/docs/react-component.html

     

    React.Component – React

    A JavaScript library for building user interfaces

    ko.legacy.reactjs.org

    Component란? 

    • React의 꽃이라 불리는 React의 핵심
    • MVC View를 독립적으로 구성해 재사용할 수 있고, 새로운 컴포넌트도 만들 수 있다.
    • 데이터(props)를 입력 받아 View 상태(state)에 따라 DOM Node를 호출한다.
    • UI를 재사용 가능한 개별적인 여러 조각으로 나누고, 각 조각을 개별적으로 나누어 코딩이 가능하다.

     어떤 것이 컴포넌트가 되어야 할지 어떻게 알 수 있을까요? 우리가 새로운 함수나 객체를 만들 때처럼 만드시면 됩니다. 한 가지 테크닉은 단일 책임 원칙입니다. 이는 하나의 컴포넌트는 한 가지 일을 하는게 이상적이라는 원칙입니다. 하나의 컴포넌트가 커지게 된다면 이는 보다 작은 하위 컴포넌트로 분리되어야 합니다.

    주로 JSON 데이터를 유저에게 보여주기 때문에, 데이터 모델이 적절하게 만들어졌다면, UI(컴포넌트 구조)가 잘 연결될 것입니다. 이는 UI와 데이터 모델이 같은 인포메이션 아키텍처(information architecture)를 가지는 경향이 있기 때문입니다. 각 컴포넌트가 데이터 모델의 한 조각을 나타내도록 분리해주세요.

    다섯개의 컴포넌트로 이루어진 앱을 한번 봅시다. 각각의 컴포넌트에 들어간 데이터는 이탤릭체로 표기했습니다. 이미지의 숫자는 아래 숫자에 해당됩니다.
    1. FilterableProductTable(노란색): 예시 전체를 포괄합니다.
    2. SearchBar(파란색): 모든 유저의 입력(user input) 을 받습니다.
    3. ProductTable(연두색): 유저의 입력(user input)을 기반으로 데이터 콜렉션(data collection)을 필터링 해서 보여줍니다.
    4. ProductCategoryRow(하늘색): 각 카테고리(category)의 헤더를 보여줍니다.
    5. ProductRow(빨강색): 각각의 제품(product)에 해당하는 행을 보여줍니다.

    https://ko.legacy.reactjs.org/docs/thinking-in-react.html#step-1-break-the-ui-into-a-component-hierarchy

    Component 트리 구조

    Component 종류

    • 함수형 Component
      • 짧고 직관적
      • Vanilla JS와 같은 기본적인 function 구조를 이용해 더 직관적이며 추상적
      • 메모리 자원을 덜 사용한다.
    • 클래스형 Component
      • State와 라이프 사이클 기능 이용 가능
      • Render 함수 필수

    클래스형 Component

    //1 방법 import { Component } from "react";
    //2 방법 import React from "react";
    //1 방법 class ClassComponent extends Component {}
    //2 방법 class ClassComponent extends React.Component {}
    
    class ClassComponent extends Component {
      //클래스형 컴포넌트에서는 render 함수는 필수
      render() {
         const name = "dongho!";
        return (
          <>
            <h1>Hello {name}</h1>
            <p>여기는 클래스형 컴포넌트</p>
          </>
        );
      }
    }
    
    export default ClassComponent;
    • 클래스 컴포넌트는 Render()가 필수이다.
    • 이렇게 컴포넌트를 만들고 상위 컴포넌트에서 아래 코드처럼 불러서 사용할 수 있다.
    import ClassComponent from "./ClassComponent";
    function App() {
      return (
          <>
            <ClassComponent />
            <ClassComponent></ClassComponent>
          </>
       );
    }
    
    export default App;

    함수형 Component

    //함수형 컴포넌트
    //function 컴포넌트명
    //const 컴포넌트명 = () => {}
    
    function FunctionComponent() {
      const myClass = "kdt8";
    
      return (
        <>
          <div>반갑습니다 {myClass}에 오신 것을 환영합니다.</div>
        </>
      );
    }
    
    export default FunctionComponent;
    • 상위 컴포넌트에서 불러오는 것은 똑같다.
    import FunctionComponent from "./FunctionComponent";
    
    function App() {
      return (
        <>
        <FunctionComponent></FunctionComponent>
        </>
      );
    }
    
    export default App;
    • export에서 default를 사용하게 되면 하나의 component만 export할 수 있다. 만약 여러개의 component가 있다면 default를 빼고 export만 사용하면 된다.

    ※ 잠깐! 복습※


    컴포넌트를 사용하게 되면 파일을 다 분리해서 만들고 하나의 파일에서 다 불러와서 사용하기에 편리하다. 

    import ClassComponent from "./ClassComponent";
    import FunctionComponent from "./FunctionComponent";
    import CircleComponet from "./CircleComponent";
    import TestComponent from "./test";
    import Test2Component from "./test2";
    import ClassPropsComponent from "./ClassPropsComponent";
    import FunctionPropsComponent from "./FunctionPropsComponent";
    function App() {
      return (
        <>
           <CircleComponet></CircleComponet>
          <br></br>
          <br></br>
          <h1>컴포넌트</h1>
          <ClassComponent />
          <FunctionComponent></FunctionComponent>
          <ClassComponent></ClassComponent>
          <test2Component></test2Component>
    
          <br></br>
          <TestComponent />
          <Test2Component /> 
    
          <ClassComponent></ClassComponent>
          <ClassComponent name="dongho"></ClassComponent> 
    
           <FunctionComponent name="부모입니다." age={12}>
            안녕
          </FunctionComponent>
          <FunctionComponent></FunctionComponent> 
    
          <ClassPropsComponent food="사과"></ClassPropsComponent>
          <ClassPropsComponent></ClassPropsComponent> 
          <FunctionPropsComponent
            title="나의 하루는 4시 40분에 시작된다."
            author="김유진"
            price="13,500원"
            type="자기계발서"
          ></FunctionPropsComponent>
        </>
      );
    }
    
    export default App;
    • 이렇게 App.js에 필요한 component만 불러와서 사용할 수 있다. 
    • 코드가 간결해지는게 보인다. (만약 똑같은 부분이 있다면 코드가 엄청 길어질텐데 한줄에 다 끝낼 수 있다.)
    • 물론 그러기 위해서는 다음 글에 나오는 props를 알아야 한다. 그래야 데이터을 넘기고 받고 할 수 있다.
    728x90
Designed by Tistory.