React의 "props"를 이해하세요!

11168 단어 React

개요


props는 Component의 속성입니다.
props.name 및 props페이지 등 어떤 데이터의 속성을 참조할 수 있는 물건을 가리킨다.
문자열, 숫자, 그룹, 대상, 함수 등은 모두 사용할 수 있으며, 기본적으로 {}로 묶어서 props를 전달한다.
저번 보도
React를 설명하는 Component!
다음번
React의 "state"를 사용하여 입력한 문자 수를 세어 보세요!

코드를 실제로 써보세요!


App.js
import React from 'react';

const App = () => {
  return (
    <div>
      <Animal name={'Micro Pig'} />
    </div>
  );
};

const Animal = props => {
  return <div>I love {props.name}</div>;
};

export default App;
함수 구성 요소 App 에서 <Animal name={'Micro Pig'} /> Animal 구성 요소에name 속성이 부여되었습니다.
그리고 함수 구성 요소Animal에서 매개 변수props를 받아들여 매개 변수return <div>I love {props.name}</div>;로 외부 입력을 참조하여 화면에 표시할 수 있다.

또한 이 애니멀 속성에 체중(weight) 속성을 부여하고 동물의 정보를 변수로 관리한다map로 하나하나 표시하면 코드는 다음과 같다.
App.js
import React from 'react';

const App = () => {
  const animalProfiles = [
    {
      name: 'Micro Pig',
      weight: 20,
    },
    {
      name: 'Lion',
      weight: 100,
    },
    {
      name: 'Penguin',
    },
  ];

  return (
    <div>
      {animalProfiles.map((profile, index) => {
        return (
          <Animal name={profile.name} weight={profile.weight} key={index} />
        );
      })}
    </div>
  );
};

const Animal = props => {
  return (
    <div>
      I love {props.name}! Max-weight is {props.weight}kg
    </div>
  );
};

Animal.defaultProps = {
  weight: 50;
}

export default App;

해설

const animalProfiles = [
    {
      name: 'Micro Pig',
      weight: 20,
    },
    {
      name: 'Lion',
      weight: 100,
    },
    {
      name: 'Penguin',
    },
  ];
이 부분에서 animalProfile[] 배열을 만들고, 산열을 사용하여name과 weight를 부여합니다.
App.js
return (
    <div>
      {animalProfiles.map((animalprofile, index) => {
        return (
          <Animal name={profile.name} weight={profile.weight} key={index} />
        );
      })}
    </div>
  );
이 부분에서 상기animalProfiles[]의 각 요소를 추출하여 Animal 구성 요소의name 속성과 weight 속성에 데이터를 전달합니다.
또 리액트에는 가상 DOM이 존재하는데 그 중 어느 DOM이 변경되었는지 관리하고 변경 점만 실제 DOM의 구조에 반영한다.따라서 어떤 DOM이 변경됐는지 지시하기 위해서는 오리지널Key이 필요하다.여기서는 map를 사용하여 indexKey로 받아서 DOM을 관리한다.
App.js
const Animal = props => {
  return (
    <div>
      I love {props.name}! Max-weight is {props.weight}kg
    </div>
  );
};

Animal.defaultProps = {
  weight: 50,
};
이 부분은 실제 부모의 구성 요소로부터 받은 props에 따라 브라우저에 렌더링됩니다.Animal.defaultProps = { weight: 50,}; 부분에서 기본 설정을 통해 수신props된 구성 요소의 값은 이번의 경우 없음weight의 데이터를 제공할 때 자동으로 주어집니다weight: 50.

출력화면 여기 있어요.



총결산


위에서 말한 바와 같이 부모가 어떤 데이터를 부모의 부품에서 아이에게 전달하고자 할 때 이것props을 크게 이용하세요!

좋은 웹페이지 즐겨찾기