React Props

1abme·2023년 3월 23일
0

React

목록 보기
2/12

Props


컴포넌트의 속성(Property)를 의미하는 props는 생년월일 처럼 변하지 않는 외부로부터 전달받은 값으로, 웹 애플리케이션에서 해당 컴포넌트가 가진 속성에 해당한다.

이는 부모 컴포넌트 (상위 컴포넌트)로 부터 전달받은 값이며 React 컴포넌트는 JavaScript함수와 클래스로 Props를 함수의 전달인자(arguments)처럼 전달받아 이를 기반으로 화면에 어떻게 표시되는 지를 기술하는 react엘리먼트를 반환한다.

때문에 컴포넌트가 최초 렌더링 될 때 화면에 출력하고자 하는 데이터를 담은 초깃값으로 사용 할 수 있다.

형태는 객체형태로 어떤 타입의 값도 넣어 전달 할 수 있으며 함부로 변경될 수 없는 읽기전용 (read-only) 객체이다. 만약 읽기 전용 객체가 아니라면 props를 전달받은 하위 컴포넌트 내에서 props를 직접 수정 시 props를 전달한 상위 컴포넌트의 값에 영향을 미칠 수 있게 됩니다.개발자가 의도하지 않은 side effect가 생기고 이는 react의 단반향, 하향식 데이터 흐름 원칙 (React is all about one-way data flow down the component hierarchy)에 위배됩니다.

props 사용법


props 사용법에는 attribute를 할당하여 사용하는 방법과 children을 할당하여 사용하는 방법이 있다.

props.attribute


props는 객체형태이기 때문에 속성및 값을 할당하는 방법인 <Child attribute={value} /> 형식으로 props를 전달 할 수 있다.

그렇게 전달받은 props는 객체형태인 {attribute: value} 형태를 띄게되고 렌더링 해야 할 때는 javascript에서 object.key 를 통해 value값에 접근 하는 것처럼 dot notation을 사용해 props.attribute으로 값에 접근하여 사용한다..

props.attribute 활용의 예)

function Parent() {
  return (
    <div className="parent">
      <h1>I'm the parent</h1>
      <Child text={"I'm the eldest child"} />
    </div>
  );
}

function Child(props) {
  // console 을 열어 props 의 형태를 직접 확인하세요.
  console.log("props : ", props);
  return (
    <div className="child">
      <p>{props.text}</p>
    </div>
  );
}

props.children


Props를 전달하는 또 다른 방법으로 여는태그와 닫는 태그 사이에 value를 넣어 전달하는 방법이 있다. 이 경우 props는 객체 형태인 {children: value} 형태를 띄며 props를 랜더링하기 위해서는 props.children을 이용해야한다.

props.childern 활용의 예)

function Parent() {
  return (
    <div className="parent">
        <h1>I'm the parent</h1>
        <Child>I'm the eldest child</Child>
    </div>
  );
};

function Child(props) {
  return (
    <div className="child">
        <p>{props.children}</p>
    </div>
  );
};
profile
제가 이해하고 있는게 맞나요...?

0개의 댓글

관련 채용 정보