[React] 프로퍼티(Props)

안세웅·2023년 4월 6일
0

React

목록 보기
5/8

프로퍼티(Props)란

  • 프로퍼티, props(properties의 줄임말) 라고 합니다.
  • 상위 컴포넌트가 하위 컴포넌트에 값을 전달할때 사용합니다.(단방향 데이터 흐름)
  • 프로퍼티는 수정할 수 없다는 특징이 있습니다.(자식입장에선 읽기 전용인 데이터)

부모 Component에서 자식 Component로 데이터 전달

부모 component에서는 전달 할 값의 key값과 value값을 자식 component호출 시 html속성 형식으로 넘겨줄 수 있습니다.

function App() {
  return (
    <div>
      <Btn text="Save Changes" big={true} />
      <Btn text="Continue" big={false} />
    </div>
  );
}
  • 프로퍼티에 문자열을 전달할 때는 큰따옴표(" ")를, 문자열 외의 값을 전달할 때는 중괄호({ })를 사용 합니다.

자식 component에서는 component의 인자값으로 받을 수 있습니다.

function Btn(props) {
  return (
    <button
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
        fontSize: props.big ? 18 : 16,
      }}
    >
      {props.text}
    </button>
  );
}

아래와 같이 다른 방법으로 도 받을 수 있습니다.

function Btn({text, big}) {
  return (
    <button
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
        fontSize: big ? 18 : 16,
      }}
    >
      {text}
    </button>
  );
}

프로퍼티에는 단순한 값 뿐만아니라 함수도 전달 할 수 있습니다.

function Btn({ text, changeValue }) {
  return (
    <button
      onClick={changeValue}
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      {text}
    </button>
  );
}

function App() {
  const [value, setValue] = React.useState("Save Changes");
  const changeValue = () => setValue("Revert Changes");
  return (
    <div>
      <Btn text={value} changeValue={changeValue} />
      <Btn text="Continue" />
    </div>
  );
}

위와 같이 부모 component의 함수를 자식 component에서 호출 할 수 있습니다.


Prop Types

자식 component로 데이터를 전달 시 우리는 실수로 string 으로 전달되어야 할 값을 number로 전달하는 실수를 할 수 있습니다.

function App() {
  return (
    <div>
      <Btn text="Save Changes" fontSize={18} />
      <Btn text={14} fontSize={"Continue"} />
    </div>
  );
}

하지만 따로 prop에 type를 설정해주지 않았기 때문에 React는 오류로 인식하지 않습니다.
이를 방지하기위해 prop에 type를 설정 해 줄 수 있습니다.

우선 type를 설정하기 위해 외부 스크립트를 추가하였습니다.
그리고 각 prop에 맞는 type를 설정 해주었습니다.

<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
function Btn({ text, fontSize }) {...}

Btn.propTypes = {
  text: PropTypes.string,
  fontSize: PropTypes.number,
};

function App() {...}

이렇게 type를 설정 해주고 로그를 확인 해보면

이와같은 에러 메세지가 나타나는 것을 확인 할 수 있습니다.

또한 component 호출 시 설정한 prop가 무조건 있어야 할 경우에 .isRequired를 추가하여 설정 할 수 있습니다.

Btn.propTypes = {
  text: PropTypes.string.isRequired,
  fontSize: PropTypes.number.isRequired,
};

아래 주소에서 다양한 type를 확인 할 수 있습니다.
https://ko.reactjs.org/docs/typechecking-with-proptypes.html


React.memo

자식 component에서 부모 component의 state값을 변경 시
부모 component가 re-rendering되기 때문에
두개의 Btn 중 첫번째 Btn의 값만 변경되었지만
두개의 Btn이 다 re-rendering 되고 있습니다.

function Btn({ text, changeValue }) {
  console.log(text, "was rendered");
  return (
    <button
      onClick={changeValue}
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      {text}
    </button>
  );
}

function App() {
  const [value, setValue] = React.useState("Save Changes");
  const changeValue = () => setValue("Revert Changes");
  return (
    <div>
      <Btn text={value} changeValue={changeValue} />
      <Btn text="Continue" />
    </div>
  );
}

해당코드로 실행 후 로그를 확인 해보면

이와같이 로그가 확인됩니다.

하지만 React.memo 함수를 사용하여 변경된 Btn만 re-rendering 할 수 있습니다.

function Btn({ text, changeValue }) {
  console.log(text, "was rendered");
  return (
    <button
      onClick={changeValue}
      style={{
        backgroundColor: "tomato",
        color: "white",
        padding: "10px 20px",
        border: 0,
        borderRadius: 10,
      }}
    >
      {text}
    </button>
  );
}

const MemorizedBtn = React.memo(Btn);

function App() {
  const [value, setValue] = React.useState("Save Changes");
  const changeValue = () => setValue("Revert Changes");
  return (
    <div>
      <MemorizedBtn text={value} changeValue={changeValue} />
      <MemorizedBtn text="Continue" />
    </div>
  );
}

위와같이 바로 Btn component로 호출하는것이 아니라
Btn component를 memorized component로 선언 후
해당 component를 호출 하여 변경된 component만 re-rendering 할 수 있습니다.

로그를 확인 해보면


이처럼 변경 된 component만 re-rendering되는 것을 확인 할 수 있습니다.



Reference

노마드 코더 ReactJS로 영화 웹 서비스 만들기
https://nomadcoders.co/react-for-beginners/lobby

0개의 댓글