Props

딱이·2021년 4월 4일
0

컴포넌트가 속성을 설정할 때 사용하는 요소.
props 값은 해당 컴포넌트를 불러와 사용하는 부모 컴포넌트에서 설정 할 수 있다.

props default 값 설정

function App(props) {...}

App.defaultProps = {
	name: "기본값"
}

propTypes를 통한 prop 검증

// import 추가
import PropTypes from "prop-types";

function App(props) {...}

App.defaultProps = {
	name: "기본값"
}

// 하단에 type 설정 추가
App.propTypes = {
	name: PropTypes.string
}

이제 name은 무조건 문자열(String) 형태로 전달 해야 된다.

만약 지정 타입과 다른 타입으로 보낸다면, 화면에서 데이터 확인은 할 수 있지만 콘솔에서 경고 메세지가 발생한다. 그러니 지정한 타입과 잘 맞추어 데이터 값을 설정해야 한다!

isRequired을 사용한 필수 검증

더 확실한 propsType 설정이 필요 할 때!

propTypes를 설정할 때, 뒤에 isRequired를 붙여주면 type 미지정 시 경고 메세지를 보내준다. (데이터 값을 설정하지 않은 경우도 type 미지정 상태이므로 체크 할 수 있다.)

App.propTypes = {
	name: PropTypes.string,
    age: PropTypes.number.isRequired
}

클래스형 컴포넌트에서의 사용

import React, {Component} from 'react';
import PropTypes from 'prop-types';

class App extends Component {
  static defaultProp = {
    name: '기본 이름'
  }

  static propTypes = {
    name: PropTypes.string,
    age: PropTypes.number.isRequired,
  }

  render() {
    const {name, age} = this.props;
      return (
          <div>
            <h1>이름 : {name}</h1>
            <h1>나이 : {age}</h1>
          </div>
      );
    }
}

export default App;
profile
뚝딱뚝딱 FE

0개의 댓글