defaultProps 란?
defaultProps : props를 따로 지정해주지 않아도 기본값으로 전달 해주는 props
defaultProps 사용법
defaultProps 사용법은 간단합니다 2가지 방법을 살펴보겠습니다.
MainComponent.js
생략 코드 => state 개념잡기 참고
방법 1.
import React, { Component, Fragment } from 'react'
export default class MainComponent extends Component {
}
MainComponent.defaultProps = {
name:"초기값"
}
// or
export default class MainComponent extends Component {
static defaultProps = {
name:"초기값"
}
}
interface Props {
text:string;
}
export const MainComponentFucntion = (props:Props) =>{
return <div>{props.text}</div>
}
MainComponentFucntion.defaultProps = {
text:'초기값'
}
컴포넌트 바깥에서 defaultProps를 지정해주기 위해서는 컴포넌트명.defaultProps = {} 로 선언 해줄 수 있으며, 객체 안에 여러 개의 defaultProps 를 선언 할 수 있다 함수형도 동일합니다.
컴포넌트 내부에서 defaultProps를 지정해주기 위해서는 static defaultProps = {} 로 선언 하여 사용 할 수 있다.
defaultProps를 통해 기본값을 지정해줌으로써 예기치 못한 오류 또한 사전에 예방할 수 있다.
'프론트엔드 > react' 카테고리의 다른 글
Typescript 병합 선언과 개별 선언 (0) | 2022.07.15 |
---|---|
Clean-up function (0) | 2022.01.24 |
[React] 컴포넌트 렌더링 이후 effect 수행하기 (0) | 2022.01.24 |
moment를 적용 하면서 (0) | 2022.01.12 |
AXIOS를 통한 서버연결 (0) | 2021.12.12 |