import styled from 'styled-components';
interface CircleProps {
bgColor: string;
}
const Circle = ({ bgColor }: CircleProps) => {
return <Container bgColor={bgColor} />;
};
const Container = styled.div<CircleProps>`
width: 200px;
height: 200px;
background-color: ${({ bgColor }) => bgColor};
border-radius: 100px;
`;
export default Circle;
해당 코드에서 bgColor은 필수적인 props이다. 만약 두 원중 하나에만 border을 적용하고 싶다면,
즉 optional props를 사용하고 싶다면 어떻게 해야 할까?
interface CircleProps {
bgColor: string;
borderColor: string;
}
interface에 borderColor을 추가하면 해당 인자는 필수라고 한다.
interface CircleProps {
bgColor: string;
borderColor?: string;
}
이렇게 선택적으로 필요할 인자의 콜론에 ?를 붙여주면 optional한 props가 된다.
import Circle from './Circle';
function App() {
return (
<div>
<Circle borderColor="black" bgColor="teal" />
<Circle text="hi there" bgColor="tomato" />
</div>
);
}
export default App;
import styled from 'styled-components';
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string;
}
const Circle = ({
bgColor,
borderColor,
text = 'default text',
}: CircleProps) => {
return (
<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
{text}
</Container>
);
//bordeerColor가 있다면 borderColor이고, undefined라면 bgColor으로 해라
};
const Container = styled.div<CircleProps>`
width: 200px;
height: 200px;
background-color: ${({ bgColor }) => bgColor};
border-radius: 100px;
border: 1px solid ${({ borderColor }) => borderColor};
`;
export default Circle;
optional props를 사용하고 text가 없을 경우 default text를 출력하게 만들 수 있다.
'1차 공부 > 공부한 자료' 카테고리의 다른 글
typescript 공부 4 (0) | 2023.01.02 |
---|---|
typescript 공부 3 (0) | 2023.01.02 |
typescript 공부1 (0) | 2023.01.02 |
221226 useMemo (0) | 2022.12.26 |
221224 socket.io / emit (0) | 2022.12.24 |