꾸준히 성장하는 개발자

[React with TypeScript] 본문

React

[React with TypeScript]

ahleum 2022. 5. 27. 18:57

Prop Types는 prop이 거기에 있는지 없는지 확인해주지만 코드를 실행한 후에만 확인이 가능하다

 

그래서 그 방법이 다닌 다른 방법을 사용해볼 수 있다

 

import styled from "styled-components";

const Container = styled.div``;

interface CircleProps {
  bgColor: string;
}

function Circle({ bgColor }: CircleProps) {
  return <Container />;
}

export default Circle;
Prop Type들을 객체로 만들어서 정의해주는것이다

interface CircleProps {
  bgColor: string;
}

 

이렇게 interface 를 적어서 prop들을 모아놓은 객체 이름을 작성하고 { } 중괄호 안에 

prop type들을 선언 해준다.

 

위처럼 

// 방법1
function Circle({ bgColor }: CircleProps) {
  return <Container  bgColor={bgColor}  />;
}

// 방법2
function Circle(props: CircleProps) {
  return <Container bgColor={props.bgColor} />;
}

이렇게 {bgColor} 이렇게 넣어서 작성해줄 수도 있지만

(props: CircleProps) 이렇게 넣어서 작성해줄수도 있다. 하지만 대부분 방법 1의 방법을 많이 사용한다.

 

 

보면 에러 메시지가 뜨고 있는데 이건 Container에 props가 선언되지 않아서 그런 것이다.

Container는 보면 div인데 이 component는 어떤 props도 받고 있지 않고 있다

 

해결방법은

 

또 다른 interface를 만들어 Container에 props를 넘겨주면 된다.

interface ContainerProps {
  bgColor: string;
}

const Container = styled.div<ContainerProps>``;

const Container = styled.div<ContainerProps>``;

그럼 에러 메시지가 없어진 것을 확인할 수 있다.

 

prop이 bgColor, otherThing이 있는데 이중에서 사용하지 않는게 있을 수 있는데 

prop을 optional(있어도 되고 없어도 되게)하게 만들기 위해서는 아래처럼 ? 를 넣어  표시해준다.

이렇게 ? 를 넣는것은 boolean 이거나 undefined라고 볼 수 있다