Coding/React

컴포넌트에 props전달 - 1

민톨이 2024. 3. 6. 09:51
728x90
  • 부모컴포넌트에서 props를 통해 자식 컴포넌트로 정보전달
  • 부모에서 props 객체전달하고 자식 컴포넌트에서 구조분해할당하여 같은 이름으로 받음
  • props는 변경불가하며 상호작용이 필요한 경우 state 사용
  • 컴포넌트 렌더링시 마다 새로운 props를 받음
// App.jsx
import { getImageUrl } from './utils.js';

function Avatar({ person, size }) {
  return (
    <img
      className="avatar"
      src={getImageUrl(person)}
      alt={person.name}
      width={size}
      height={size}
    />
  );
}

export default function Profile() {
  return (
    <div>
      <Avatar
        size={100}
        person={{
          name: 'Katsuko Saruhashi',
          imageId: 'YfeOqp2',
        }}
      />
      <Avatar
        size={80}
        person={{
          name: 'Aklilu Lemma',
          imageId: 'OKS67lh',
        }}
      />
      <Avatar
        size={50}
        person={{
          name: 'Lin Lanying',
          imageId: '1bX5QH6',
        }}
      />
    </div>
  );
}
// utils.js
export function getImageUrl(person, size = 's') {
  return `https://i.imgur.com/${person.imageId}${size}.jpg`;
}
  • props 사용하여 부모와 자식 컴포넌트를 독립적으로 사용가능
  • props객체는 함수실행시 전달되는 인자와 동일
// App.jsx
// 아바타 컴포넌트에서 props 사용방식 변경
function Avatar({ person, size }) {
  return (
    <>
      <div>
        <img
          className="avatar"
          src={getImageUrl(person)}
          alt={person.name}
          width={size}
          height={size}
        />
      </div>
      <strong>{person.name}</strong>
    </>
  );
}

 

prop 기본값 지정

-prop이 없거나 undefined일 경우 기본값 사용

// App.jsx
function Avatar({ person, size = 150 }) {
  return (
    <>
      <div>
        <img
          className="avatar"
          src={getImageUrl(person)}
          alt={person.name}
          width={size}
          height={size}
        />
      </div>
      <strong>{person.name}</strong>
    </>
  );
}