이번에는 props 데이터 중에 값이 없는 경우 기본 값을 설정하는 방법에 대해 알아보겠습니다.
자 그럼,Device.js 파일을 수정해보겠습니다.
Device에 cpu를 추가하겠습니다. 실제로 cpu에 대한 데이터는 받고있지 않습니다.
import React from 'react';
import PropTypes from 'prop-types';
function Device( {name, ram, homeButton, touchID, faceID, cpu} ) {
return (
<div>
<h3>Name : {name}</h3>
<h3>RAM : {ram}</h3>
<h3>Home Button : {homeButton}</h3>
<h3>TouchID : {touchID}</h3>
<h3>FaceID : {faceID}</h3>
<h3>CPU : {cpu}</h3>
</div>
);
}
Device.propTypes = {
name: PropTypes.string.isRequired,
ram: PropTypes.number.isRequired,
homeButton: PropTypes.bool.isRequired,
touchID: PropTypes.string,
faceID: PropTypes.string,
};
export default Device;
보는것과 같이 CPU데이터는 받고있지 않기 때문에 값이 나타나지 않습니다.
그럼 이렇게 값이 없을 때 어떻게 기본값을 설정하는 방법에 대해 알아봅시다.
이럴 땐 defaultProps를 사용합니다.
defaultProps는 다음과 같이 사용합니다.
컴포넌트명.defaultProps = {
props명 : 기본값,
};
즉, 예를 들어 cpu의 기본값을 'cpu정보가 없습니다.' 라고 한다면
Device.defaultProps = {
cpu : "cpu정보가 없습니다.",
};
자, 그럼 적용해봅시다.
import React from 'react';
import PropTypes from 'prop-types';
function Device( {name, ram, homeButton, touchID, faceID, cpu} ) {
return (
<div>
<h3>Name : {name}</h3>
<h3>RAM : {ram}</h3>
<h3>Home Button : {homeButton}</h3>
<h3>TouchID : {touchID}</h3>
<h3>FaceID : {faceID}</h3>
<h3>CPU : {cpu}</h3>
</div>
);
}
Device.defaultProps = {
cpu : "cpu정보가 없습니다.",
};
Device.propTypes = {
name: PropTypes.string.isRequired,
ram: PropTypes.number.isRequired,
homeButton: PropTypes.bool.isRequired,
touchID: PropTypes.string,
faceID: PropTypes.string,
};
export default Device;
defaultProps에 대해서 알아봤습니다.
그런데 지금보니 Home Button 값도 안나오네요. 다음시간에는 값이 나오게끔 수정해봅시다.
봐주셔서 감사합니다. 문의 또는 잘못된 설명은 아래의 댓글에 부탁드립니다.
당신의 작은 누름이 저에게는 큰 희망이 됩니다.
댓글 0개
정렬기준