본문 바로가기
WebDev/항해99

스타일컴포넌트/타입스크립트 사용 - 프랍 시 $ or as prop

by S.AHA_dev 2023. 8. 19.
728x90
반응형

1차 발표가 끝난 후 콘솔에 나오는 에러를 잡는 중 발견한 에러

 

스타일드컴포넌트 라이브러리를 타입스크립트와 함께 사용할 때,

프랍에 명시적으로 스타일 프랍인지 설정해주지 않아서 나타나는 오류가 있었다.

해결방안으로

$

$ 이 기호를 사용하는 이유는 명시적으로 스타일 프로퍼티를 구별하기 위함

타입스크립트와 함께 사용할 때, $ 기호가 없으면

컴포넌트의 일반 프로퍼티와 스타일 프로퍼티가 충돌할 수 있다. 

스타일드 컴포넌트에 추가적인 타입 정의와 함께 사용될 떄

$ 기호는 styled-components에서 사용된다는 것을 명확하게 나타냄.

import styled from 'styled-components';

type ButtonProps = {
  $bgcolor: string;
};

const Button = styled.button<ButtonProps>`
  background-color: ${(props) => props.$bgcolor};
`;

 

as prop

as prop를 사용하여 컴포넌트의 기본 태그를 대체 가능

이렇게 하면 기본 HTML 엘리먼트가 상속하는

속성과 사용자 정의 속성 간의 충돌을 최소화

import styled from 'styled-components';
import { ButtonHTMLAttributes } from 'react';

type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
  bgcolor: string;
};

// ButtonProps 타입을 매개변수로 전달합니다.
const Button = styled.button<ButtonProps>`
  background-color: ${(props) => props.bgcolor};
`;
반응형

'WebDev > 항해99' 카테고리의 다른 글

실전프로젝트 회원가입 로직  (2) 2023.08.21
로그인 ui 최적화  (0) 2023.08.19
.stopPropagation()  (0) 2023.08.18
실전프로젝트 분담 변경  (0) 2023.08.11
실전프로젝트 로그인 로직 정리  (0) 2023.08.07