Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- typescript react
- react typescript
- ngrok실행
- API 토큰
- API token
- github io
- CSS
- ngrok설치
- Git
- fetch
- styled components
- 컨디셔널 렌더링
- input type=file
- getModifierState
- There isn’t anything to compare
- createGlobalStyle
- rewrites
- git lab
- react env
- nextjs
- react
- dart 변수
- next.js css
- icon
- nextjs 설치
- npm styled-reset
- bootstrap
- nextjs .env
- github
- SCSS
Archives
- Today
- Total
꾸준히 성장하는 개발자
[React with TypeScript] 본문
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라고 볼 수 있다
'React' 카테고리의 다른 글
[React] styled-reset _1 (npm i styled-reset) (0) | 2022.06.07 |
---|---|
[React] 컨디셔널 렌더링 ?? (0) | 2022.05.31 |
[React Hooks] useEffect( ) (0) | 2022.05.25 |
[React Hooks] useMemo() / useCallback() / useMemo() ↔ React.memo() 차이 (0) | 2022.05.24 |
[React Hooks] useRef (0) | 2022.05.23 |