728x90
반응형
타입스크립트에서는 타입을 선언해주기 위해
interface를 생성해주고 그 안에 해당 변수에 대한 타입을 작성한다.
interface CircleProps{
bgColor: string; // default
borderColor?: string; // optional
text?: string; // optional
}
Circle 컴포넌트가 있다고 가정을 하자
interface CircleProps 내 변수의 타입을 선언하는데
일반적인 콜론(:)을 사용한다면 반드시 string에 해당하는 값을 작성해주어야 한다.(default)
하지만 물음표콜론(?:)을 사용하게되면 borderColor: string | undefined와 동일한 의미로
값이 들어가지 않아도 되는 optional value가 된다.
[참고예제]
// Circle.tsx
import React from 'react';
import styled from 'styled-components';
interface ContainerProps{
bgColor: string; // default
borderColor: string; // default
}
interface CircleProps{
bgColor: string; // default
borderColor?: string; // optional
text?: string; // optional
}
const Container = styled.div<ContainerProps>`
width : 200px;
height: 200px;
border-radius: 100px;
background-color: ${(props) => props.bgColor}; // default 때문 작성
border: 1px solid ${(props) => props.borderColor} // default 때문 작성
`;
// text = "default text"는 default value를 설정해준 것
const Circle = ({bgColor, borderColor, text="default text"}: CircleProps) => {
return (
<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>{text}</Container>
);
}
export default Circle;
// App.tsx
import React from 'react';
import './App.css';
import styled, { keyframes } from 'styled-components';
import Circle from './Circle';
function App() {
return (
<div>
<Circle bgColor='yellow' borderColor='blue'/>
<Circle bgColor='tomato' text='hi'/>
</div>
);
}
export default App;
728x90
반응형