본문 바로가기
카테고리 없음

react - Component로 props 전달하기(Passing Props to a Component)

by 룰루리랄라리 2021. 11. 3.

Component로 props 전달하기(Passing Props to a Component)

React의 Component는 props를 사용하여 서로 객체, 배열 및 함수를 포함하여 모든 자바스크립트 값등의 데이터를 주고받는다.

Familiar props

props는 JSX 태그에 전달하는 정보를 의미한다.
아래의 코드에서 img 태그 안에 있는 className, src, alt, width, and height 는 정보를 전달하기 때문에 props라고 한다.

function Avatar() {
  return (
    <img
      className="avatar"
      src="https://i.imgur.com/1bX5QH6.jpg"
      alt="Lin Lanying"
      width={100}
      height={100}
    />
  );
}

component에 props를 전달하는 방법(Passing props to a component)

export default function Profile() {
  return (
    <Avatar />
  );
}

Step 1: Pass props to the child component

Avatar component에 person과 size라는 props를 추가한다.

export default function Profile() {
  return (
    <Avatar
      person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }}
      size={100}
    />
  );
}

Step 2: Read props inside the child component

child component 안에서 props를 읽는다.

function Avatar({ person, size }) {
  // person and size are available here
}

Props를 사용하면 parent component와 child component를 독립적으로 생각할 수 있다. 예를 들어 Profile가 person과 size props를 어떻게 다루는지 생각할 필요가 없습니다. props만 변경해주면 Avatar는 변경된다.
사실 props는 component의 유일한 인수입니다. React component functions는 props object인 단일 인수를 받아들인다. 보통은 아래처럼 props 전체를 받을 필요는 없다.

function Avatar(props) {
  let person = props.person;
  let size = props.size;
  // ...
}

destructuring 문법

function Avatar({ person, size }) {
  // ...
}

props의 기본값 지정 (Specifying a default value for a prop)

와 같이 size 정보가 없거나, size={undefined} 이면 기본값이 설정된다.
하지만 size={null}, size={0}은 기본값으로 설정되지 않으니 주의해야한다.

function Avatar({ person, size = 100 }) {

}

props를 JSX spread syntax으로 전달(Forwarding props with the JSX spread syntax)

아래의 코드는 모든 props들이 전달되고 있다. 이처럼 사용해도 되지만 코드를 간결하게 표현하기 위해서는 JSX spread syntax를 사용하면 된다.

function Profile({ person, size, isSepia, thickBorder }) {
  return (
    <div className="card">
      <Avatar
        person={person}
        size={size}
        isSepia={isSepia}
        thickBorder={thickBorder}
      />
    </div>
  );
}

JSX spread syntax 적용
이렇게 하면 props의 이름들은 나열하지 않아도 모두 전달된다.
하지만 spread syntax 은 제한적으로 사용해야한다. 모든 component에 사용한다면

function Profile(props) {
  return (
    <div className="card">
      <Avatar {...props} />
    </div>
  );
}

Passing JSX as children

JSX 자체를 props로 child component에 전달할 수도 있다.
children이라는 props에 가 전달되어 온다.

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}

export default function Profile() {
  return (
    <Card>
      <Avatar
        size={100}
        person={{ 
          name: 'Katsuko Saruhashi',
          imageId: 'YfeOqp2'
        }}
      />
    </Card>
  );
}

How props change over time

Props는 항상 고정되어 있는 값이 아니다. 처음이 아니라 특정 시점의 component's의 데이터를 전달한다.
그러나 props는 변경할 수 없는 값이다.(변경을 시도해서도 안된다.) component가 props값을 변경해야하는 경우 parent component에게 새로운 props를 요청해야한다.
요청을 하면 이전 props는 폐기되고, JavaScript 엔진은 해당 props의 메모리를 회수한다.

 

https://beta.reactjs.org/learn/passing-props-to-a-component

 

Passing Props to a Component

A JavaScript library for building user interfaces

beta.reactjs.org

 

댓글