1차 공부/React공부

proptypes

공대탈출 2022. 11. 25. 19:45
npm install --save prop-types

터미널에 입력해 prop-types 설치.

import React from 'react';
import PropTypes from 'prop-types';

function App() {
  return <GrandFather />;
}

function GrandFather() {
  const name = '전상국';
  return <Mother grandFatherName={name} />;
}

function Mother(props) {
  return <Child grandFatherName={props.grandFatherName} />;
}
Child.propTypes = {
  grandFatherName: PropTypes.string,
};
function Child({ grandFatherName }) {
  return <div>{grandFatherName}</div>;
}

export default App;

import 해주고 사용.

 

특정 객체에 prop되는 것이 특정 타입인지 검사해줌.

Child.propTypes = {
  grandFatherName: PropTypes.string,
};

여기서 보면 Child에 prop되는 값들중 grandFatherName이 string인지 검사해 주는 기능.

만약 number, bool, func, array, object, symbol 이중 한 형식이라면, '콘솔창'에 오류를 찍어낸다.

 

위의 코드에서 GrandFather로부터 Mother을통해 Child에게 전해진 props의 grandFatherName는

string형식이므로 아무런 오류를 찍어내지 않는다.

 

관련된 더 많은 내용은 공식문서를 참고한다.

 

PropTypes와 함께 하는 타입 검사 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

'1차 공부 > React공부' 카테고리의 다른 글

State란?  (0) 2022.11.25
defaultProps 지정방법  (0) 2022.11.25
JSX문법 규칙  (0) 2022.11.25
렌더링이란 무엇일까?  (0) 2022.11.25
Prop Drilling  (0) 2022.11.25