[react] TypeScript

노휴일·2023년 5월 2일

react

목록 보기
6/7

TypeScript

TypeScript is JavaScript with syntax for types

프로그래밍 언어가 작동하기 전에 type을 확인!

  • 프로그램이 작동하기 전에 ts가 데이터 타입이 다르다고 이야기함

1. 사용하기

설치를 해야겠죠?

npx create-react-app 내 앱 이름 --template typescript
npm i --save-dev @types/styled-components
npm i styled-components

스타일 컴포넌트도 설치해줘요~

하 밥 먹었더니 졸림 서류 제출하고 다시 ㄱㄱ

2. 적용하기

인터페이스 : object을 설명해줌

 <Circle bgColor={'teal'} />

자 먼저 app.js에서 이렇게 넘겨줄겁니다.

function Circle({ bgColor }: CircleProps) {
    return <Container bgColor={bgColor} />;
}

자 얘는 일단

  • bgColor : props를 app.js에서 받습니다.
  • CircleProps : interface로 설명을 해줘요 여기서 아래가 CirclePorps의 interface
interface CircleProps {
    bgColor: string;
}
  • ㅇㅎ bgColor는 CircleProps 안에 있고 string type이겠다~
  • 그리고 Container에 다시 props를 넘겨줍니다
const Container = styled.div<CircleProps>`
    width: 200px;
    height: 200px;
    background-color: ${(props) => props.bgColor};
`;
  • Container 스타일 컴포넌트는 저렇게 CirclePorps로 연결되어 있죵?
    왜지.. 왤까
  • ts에게 Container가 bgColor를 받을거라고 이야기해주는 용도입니다~
  • Container가 받는 props (Circle.ts 에서)를 ts에게 잘 설명해주겠지~?

-> 이해 완

Optional Props

있어도 ㄱㅊ 없어도 ㄱㅊ은 props 만들기

props? : type

  • 물음표를 붙이면 됨

초기값 주기

props?? 값

<Container bgColor={bgColor} borderColor={borderColor ?? bgColor} />

초기값 주기 하나 더!

function Circle({ bgColor, borderColor, text = 'default text' }: CircleProps) 

저렇게 해도 ㄱㄴ~

State

state를 만들면 type이 변하는 경우 거의 없음

const [value, setValue] = useState<number | string>(1);
  • value의 값이 number혹은 string으로 타입 사용 가능

  • 빈칸으로 두면? undefined~

타입스크립트 또또캐~~

form

form을 만들어봐요

  • any type 사용 ㄴㄴ
const onChange = (event: React.FormEvent<HTMLInputElement>) => {};
  • event는 form에서 왔어요
  • onChange 함수는 HTMLInputElement에 의해서 실행될 것

-> 우리가 어떤 이벤트를 받는지 알 수 있음

자 그러면 얘는 무엇일까

 const {
            currentTarget: { value },
        } = event;
        setValue(value);
const value = event.currentTarget.value

랑 똑같습니다.

그럼 왜? 저렇게 쓸까요?? (강의 댓글 참고함)

currentTarget 안에서 여러개 값을 가져오고 싶을 때

const value = event.currentTarget.value;
const tagName = event.currentTarget.tagName;
const width = event.currentTarget.width;
const id = event.currentTarget.id;
const {
	currentTarget : {value, tagName,width, id}
} = event ;

보자마자 이해 완

Themes

1. 스타일컴포넌트 설치하기

https://styled-components.com/docs/api#typescript

2. declarations file

styled.d.ts 파일 생성하기

import 'styled-components';

declare module 'styled-components' {
    export interface DefaultTheme {
        textColor: string;
        bgColor: string;
        btnColor: string;
    }
}
  • 이렇게 테마들에 대해서 type을 지정해줘요

3. theme.ts 테마 만들기

export const lighttheme: DefaultTheme = {
    bgColor: 'white',
    textColor: 'black',
    btnColor: 'tomato',
};
  • 테마를 만들어주고 export 해줍니다!

4. index에 테마 적용

<ThemeProvider theme={dartTheme}>
  • themeProvider로 테마를 주기

5. 사용하기

const H1 = styled.h1`
    color: ${(props) => props.theme.textColor};
`;
  • 그러면 이렇게 사용이 가능함
  • ts는 props이름에서 오타가 나면 컴파일 하지 않는다! 똑똑해~~

0개의 댓글