일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- height속성
- 인접 형제 결합자
- html tag i
- RGBA
- html 태그
- Checked 의사 클래스
- padding 속성
- iframe 태그
- 아두이노
- sub태그
- css
- reveal in file explorer
- tag html
- br 태그
- html
- sup태그
- 자식결합자
- width속성
- id 선택자
- 임베디드
- iframe
- go live
- Live Server
- 전체 선택자
- background-color 속성
- not 의사클래스
- focus 의사클래스
- RGB
- i 태그
- 일반 형제 결합자
- Today
- Total
so woon!
[TYPESCRIPT] optional props 본문
학습일 : 2023. 03. 31
interface를 만들면 반드시 required가 되어서 꼭 작성해주어야 하는데
(작성해주지 않으면 빨간줄이 뜨게 됨.)
그렇게 하고 싶지 않다면?
즉, 선택적으로 사용하고 싶다면 어떻게 해야할까?
바로 optional props로 만들면 되는데
적용방법은 아래와 같다.
<Circle.tsx>
이런식으로 interface 작성시
선택적으로 사용하고 싶은
borderColor옆에 ?를 붙여주면 된다.
interface CircleProps {
bgColor: string; // required. 필수적으로 사용해야함.
borderColor?: string; // optional. 사용해도 되고 안해도 됨.
}
전체코드
<Circle.tsx>
Container 컴포넌트 styled-component 정의해준 부분에서
작성한 css 속성들에는 optional props 여부를 표시하지 않는다.
optional props여부는 interface에서 해주면 된다.
아래 코드에서는 interface가 두개(ContainerProps, CircleProps) 인데
optional props를 좀 더 이해하기 쉽기 때문에 잠시 그렇게 만들어 놓은 것이다.
원래는
ContainerProps interface 작성 부분을 다 지우고
Container styled-component 부분에
const Container = styled.div<CircleProps> 의 형태로 작성해주면 된다.
아래 Circle Props 작성 부분에서
Container 컴포넌트 리턴시
borderColor={borderColor ?? "yellow"}
의 의미는 borderColor는 사용자가 입력한 color를 따르겠지만
입력을 해주지 않는다면 (undefined) yellow를 기본값으로 설정하겠다는 뜻이다.
import styled from "styled-components";
// interface
interface ContainerProps {
bgColor: string; // CircleProps 상태랑 똑같이 만들어주어야 함.
borderColor?: string; // CircleProps 상태랑 똑같이 만들어주어야 함.
}
interface CircleProps {
bgColor: string; // required. 필수적으로 사용해야함.
borderColor?: string; // optional. 사용해도 되고 안해도 됨.
}
// styled-component
const Container = styled.div<ContainerProps>`
width: 5rem;
height: 5rem;
background-color: ${(props) => props.bgColor};
border-radius: 100px;
border: 0.5rem solid ${(props) => props.borderColor};
// css에서 borderColor는 optional 상태가 아니다. optional 표시는 interface에서!
`;
// Circle Props
// bgColor의 타입은 CircleProps의 오브젝트다 라고 말해주고 있는격
// borderColor를 styled-component인 Container로 보내준다.
// borderColor는 optional이다. 위 interface에서 그렇게 정의해줬기 때문
// borderColor={borderColor ?? "yellow"} 의 뜻
// 사용자가 입력한 color를 따르겠지만, undefined면 yellow로 설정하겠다는 뜻.
function Circle({ bgColor, borderColor }: CircleProps) {
return <Container bgColor={bgColor} borderColor={borderColor ?? "yellow"} />;
}
export default Circle;
<App.tsx>
여기서 두개의 <Circle /> 이 있는데
하나에는 bgColor, borderColor 모두 있고
나머지 하나에는 borderColor가 빠져있다.
위 Cirlce.tsx 파일에서 interface 작성시
borderColor 를 optional props로 만들어주지 않았다면
분명 에러가 났을 것이다.
import styled from "styled-components";
import Circle from "./Circle";
function App() {
return (
<div>
<Circle bgColor="teal" borderColor="black" />
<Circle bgColor="red" />
</div>
);
}
export default App;
실행결과
+ typescript는 아니지만 한가지 팁
<argument 에서 default 값 설정 방법 (ES6 Javascript 구문임)>
원한다면 default 값을 argument에서 설정할 수 있다.
방법은 아래와 같다.
<Circle.tsx>
interface에서 text?: string;
하여 optional prop으로 만들어 준다음
밑에 Circle에서 argument로 text를 전달해주면서
text = "text가 없으면 표시될 문구를 작성" 해준다.
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string;
}
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
return (
<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
{text}
</Container>
);
}
export default Circle;
전체코드
<Cirlcle.tsx>
import styled from "styled-components";
// interface
interface ContainerProps {
bgColor: string;
borderColor: string;
}
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string; // 1. text를 optional prop으로 작성해줌
}
// styled-component
const Container = styled.div<ContainerProps>`
width: 6rem;
height: 6rem;
background-color: ${(props) => props.bgColor};
border-radius: 100px;
border: 0.5rem solid ${(props) => props.borderColor};
`;
// Circle Props
// 2. text를 argument로 받아주고 = "... " 를 작성하여 default text를 설정해줌
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
return (
<Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
{text}
</Container>
);
}
export default Circle;
<App.tsx>
import styled from "styled-components";
import Circle from "./Circle";
function App() {
return (
<div>
<Circle bgColor="teal" borderColor="black" />
<Circle bgColor="red" />
</div>
);
}
export default App;
실행결과
text를 작성해주지 않았기 때문에 default 값인
"default text" 가 출력되어 나옴.
반면, 한군데에 text를 작성해준다면
import styled from "styled-components";
import Circle from "./Circle";
function App() {
return (
<div>
<Circle bgColor="teal" borderColor="black" />
<Circle bgColor="red" text="안녕" />
</div>
);
}
export default App;
실행결과
적어준 text 가 잘 반영되어
"안녕" 이 출력됨을 볼 수 있다.
'Typescript > 개념정리' 카테고리의 다른 글
[TYPESCRIPT] form 구현, form에 타입 적용하기 (0) | 2023.04.01 |
---|---|
[TYPESCRIPT] state, generic (0) | 2023.03.31 |
[TYPESCRIPT] interface 사용하기 (0) | 2023.03.30 |
[TYPESCRIPT] typescript project의 시작 (0) | 2023.03.30 |
[TYPESCRIPT] Typescript 개요 (0) | 2023.03.29 |