React default props

modric·2024년 4월 23일

defaultProps는 지양

컴포넌트의 props의 width, height를
defaultProps로 구현했는데 콘솔 창에 더이상 이용되지 않는다는 경고 에러가 떴다.
app-index.js:35 Warning: Canvas: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.

기존의 클래스형 컴포넌트보다 함수형 컴포넌트가 더 널리 사용되면서 클래스형 컴포넌트를 위해 사용했던 defaultProps는 deprecate될 예정이라고 한다.

해결방법 with TypeScript

typescript를 사용하고 있기 때문에 default parameter를 쓰면 된다. optional parameter와 default parameter를 지원하고 있기 때문에 다음 방법이 가능하다.

1. 모든 파라미터가 optional parameter일 때

interface CanvasProps {
  width?: number;
  height?: number;
}


export default function Canvas({width = 207.8, height = 589.6 }: CanvasProps) {
...
}

또는

interface CanvasProps {
  width?: number;
  height?: number;
}

const defaultProps: CanvasProps = {
  width: '207.8',
  height: '589.6'

export default function Canvas(props: CanvasProps) {

...
}
Canvas.defaultProps = defaultProps;

2. optional parameter와 required parameter가 같이 있을 때

나의 경우 모든 파라미터가 optional이라 문제가 없었지만 필수 파라미터가 있다면 다음과 같이 코드를 작성해야한다.

주의할 것은 optional parameter은 필수 파라미터 뒤에 나와야한다.
error TS1016: A required parameter cannot follow an optional parameter.

interface Props {
  name: string;
  surname?: string;
  age?: number;
}

const defaultProps = {
  surname: 'Doe',
};

function MyComponent(propsIn: Props) {
  const props = {...defaultProps, ...propsIn};

  return <div>{props.surname}</div>;
}
import * as React from "react";

// Required props
interface IFancyTitleRequiredProps {
  title: string;
}

// Optional props
interface IFancyTitleOptionalProps {
  color: string;
  fontSize: number;
}

// Combine required and optional props to build the full prop interface
interface IFancyTitleProps
  extends IFancyTitleRequiredProps,
    IFancyTitleOptionalProps {}

// Use the optional prop interface to define the default props
const defaultProps: IFancyTitleOptionalProps = {
  color: "red",
  fontSize: 40,
};

// Use the full props within the actual component
const FancyTitle = (props: IFancyTitleProps) => {
  const { title, color, fontSize } = props;
  return <h1 style={{ color, fontSize }}>{title}</h1>;
};

// Be sure to set the default props
FancyTitle.defaultProps = defaultProps;

export default FancyTitle;

참고

profile
안녕하세요 카페에서 코딩하면 안 일어나기 라는 일을 잘합니다

0개의 댓글