6. Props

cheonbi·2024년 12월 11일
0

React

목록 보기
8/11

컴포넌트의 큰 장점
-> 재사용성

Can Reuse React Components
But Don't Have To!

한번만 사용하는 컴포넌트를 구축하는 일도 있다.

한 컴포넌트의 형태는 계속 사용하지만
데이터가 다를경우는?

Configuring Components With Props

React allows you to pass data to components via a concept called Props

  1. JSX Code that use a Component
  • Set component input data via custom HTML attributes(props)

Set Props

  1. Component
  • Defines internal logic + JSX code that should be rendered

Receive Props

  1. Component function
  • Receives props parameter with configuration data

다른 데이터로 자바스크립트 기능을 구축하고 재사용 하듯
입력데이터가 다른 특정 리액트 컴포넌트를 구축하고 재사용

데이터를 컴포넌트로 전달하고 그 데이터를 그 곳에 사용

단일 Prop 객체 전달
자바스크립트 객체로 이미 구성된 데이터가 있다면,
그 객체를 여러 Prop들로 나누는 대신 하나의 Prop 값으로 전달

<CoreConcept
  title={CORE_CONCEPTS[0].title}
  description={CORE_CONCEPTS[0].description}  
  image={CORE_CONCEPTS[0].image} />

OR

<CoreConcept
  {...CORE_CONCEPTS[0]} />

이처럼 컴포넌트에 하나의 Prop를 전달할 수 있습니다 (Prop 이름은 선택적):

<CoreConcept
  concept={CORE_CONCEPTS[0]} />

그러면 컴포넌트에서는 그 하나의 Prop만 받게 됨

export default function CoreConcept({ concept }) {
  // Use concept.title, concept.description etc.
  // Or destructure the concept object: const { title, description, image } = concept;
}

어떤 문법과 접근 방식을 선호하는지는 선택

받은 Prop들을 단일 객체로 그룹화

여러 Prop을 컴포넌트에 전달한 다음, 컴포넌트 함수 내에서 자바스크립트의
"Rest Property" 문법을 사용하여 단일 객체로 그룹화

예를 들어, 컴포넌트가 이런 식으로 사용되었다면:

<CoreConcept
  title={CORE_CONCEPTS[0].title}
  description={CORE_CONCEPTS[0].description}  
  image={CORE_CONCEPTS[0].image} />

받은 prop들을 다음과 같이 단일 객체로 그룹화할 수 있습니다:

export default function CoreConcept({ ...concept }) { 
  // ...concept groups multiple values into a single object
  // Use concept.title, concept.description etc.
  // Or destructure the concept object: const { title, description, image } = concept;
}

기본 Prop 값
가끔 선택적 Prop을 받을 수 있는 컴포넌트를 만들게 될 때가 있습니다.
예를 들어, ‘type’ Prop을 받을 수 있는 커스텀 Button 컴포넌트가 있을 때
type 설정 여부와 상관 없이 모두 사용할 수 있어야 합니다.

type 설정이 된 경우:

<Button type="submit" caption="My Button" />

되지 않은 경우:

<Button caption="My Button" />

이 컴포넌트가 작동하도록 하려면, type Prop에 대한 기본 값을 설정
⏩ 전달되지 않을 경우를 대비

자바스크립트는 객체 비구조화를 사용할 때 기본 값을 지원

export default function Button({ caption, type = "submit" }) { 
  // caption has no default value, type has a default value of "submit" 
}
profile
༼ つ ◕_◕ ༽つ

0개의 댓글