React : Props & Components

코일·2022년 1월 6일
0

learn-react

목록 보기
1/4
post-thumbnail

Components and Props

https://ko.reactjs.org/docs/components-and-props.html#gatsby-focus-wrapper

컴포넌트를 통해 주입해준 값 , 프로퍼티 (속성)

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

이 예시에서는 다음과 같은 일들이 일어납니다.

  1. <Welcome name="Sara" /> 엘리먼트로 ReactDOM.render()를 호출합니다.
  2. React는 {name: 'Sara'}를 props로 하여 Welcome 컴포넌트를 호출합니다.
  3. Welcome 컴포넌트는 결과적으로 <h1>Hello, Sara</h1> 엘리먼트를 반환합니다.
  4. React DOM은 <h1>Hello, Sara</h1> 엘리먼트와 일치하도록 DOM을 효율적으로 업데이트합니다.

주의: 컴포넌트의 이름은 항상 대문자로 시작합니다.


컴포넌트 합성 = Composition

컴포넌트는 자신의 출력에 다른 컴포넌트를 참조할 수 있습니다. 이는 모든 세부 단계에서 동일한 추상 컴포넌트를 사용할 수 있음을 의미합니다. React 앱에서는 버튼, 폼, 다이얼로그, 화면 등의 모든 것들이 흔히 컴포넌트로 표현됩니다.

예를 들어 Welcome을 여러 번 렌더링하는 App 컴포넌트를 만들 수 있습니다.

// App.js

import Composition from "./components/2-4.Props/Composition";

function App() {
  return (
    <div className="App">
      <Composition />
    </div>
  );
}

export default App;

컴포넌트 추출

컴포넌트를 여러 개의 작은 컴포넌트로 나누는 것을 두려워하지 마세요.

다음 Comment 컴포넌트를 살펴봅시다.

예제 코드

import React from "react";

function formatDate(date) {
  return date.toLocaleDateString();
}

function Avatar(props) {
  return (
    <img className="Avatar" src={props.user.avatarUrl} alt={props.user.name} />
  );
}

function UserInfo(props) {
  return (
    <div className="UserInfo">
      <Avatar user={props.user} />
      <div className="UserInfo-name">{props.user.name}</div>
    </div>
  );
}

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
      <div className="Comment-text">{props.text}</div>
      <div className="Comment-date">{formatDate(props.date)}</div>
    </div>
  );
}

const comment = {
  date: new Date(),
  text: "I hope you enjoy learning React!",
  author: {
    name: "Hello Kitty",
    avatarUrl: "https://placekitten.com/g/64/64",
  },
};

export default function Extraction() {
  return (
    <div>
      <Comment
        date={comment.date}
        text={comment.text}
        author={comment.author}
      />
    </div>
  );
}

왜 이렇게 나누면서까지 컴포넌트를 추출하는지 !?

재사용성을 높이기 위해 나누는 것.

props 는 읽기전용이다. 입력 값을 바꾸지말고 쓰기만 하라. ( 순수 함수 )


정리

Props

props → 컴포넌트에 전달되는 단일 객체

순수함수처럼 동작 → Props 자체를 수정해서는 안됨

컴포넌트 합성 → 여러 컴포넌트를 모아서

컴포넌트 추출 → 여러곳에서 사용되거나 (재사용) / 복잡한 경우 (간결성, 가독성)


profile
How do you get what you want?🤔🤔

0개의 댓글