공부기록/Typescript (26) 썸네일형 리스트형 React Typescript Webpack setup 해보기 새로운 폴더에서 src, build 폴더 만들기 package.json npm init 으로 package json파일 만들기 index.html index.html파일 만들기 body에 id root를 가진 div태그 만들기 패키지 설치 npm install react react-dom // react패키지 npm install -D typscript @types/react @types/react-dom //typescript 패키지 tsconfig.json파일 만들고, 설정파일 입력 src에 App.tsx파일 만들고 내용 입력 index.tsx파일 만들고 내용입력 (엔트리 포인트가 될 파일) 추가 패키지 설치 리액트코드는 브라우저에서 이해하지 못함 ✨babel✨은 react와 typescript코드를.. Data fetching 타입지정해보기, useEffect에서 async fetch의 타입 BlogPosts컴포넌트에 프롭으로 전달 error객체의 타입 지정 fetch의 타입 프로미스를 반환함 프로미스는 제네릭 타입인데 어떤 값을 생성할 프로미스 response 객체 response는 브라우저에서 제공되는 또다른 타입 (Response) response.json()으로 JSON데이터를 얻을 수 있음 .json은 promise를 또 반환 그런데 백엔드로부터 받는 데이터가 어떤 형식인지 모르므로 any타입으로 지정될 수밖에 없음 참고 : Zod 라이브러리 데이터를 유효성 검사하고 유효성 검사 결과에 따라 TypeScript에서 자동으로 타입을 추론할 수 있게 해줌 임시방편 as const data = response.json() as unknown; any보단 나은것이 unkn.. #76 setInterval은 useEffect안에 넣자 setState로 상태 업데이트를 하게 되면 컴포넌트를 다시 실행되고, 컴포넌트가 실행될 때마다 새 interval이 실행될 것이다. 이전 interval도 계속 실행되어 실제로 무한루프에 빠진다. setInterval(function () { setRemainigTime((prev) => prev - 50); }, 50); 그러므로 useEffect에 넣고 뎁스를 비워두면 컴포넌트가 렌더링 된 뒤 setInterval은 한번만 실행된다. import Container from "./UI/Container.tsx"; import { type Timer as TimerProps } from "../store/timers-context.tsx"; import.. # 65 Context Api 타입지정 베이스 셋업 import { createContext } from "react"; type Timer = { name: string; duration: number; }; type TimersState = { isRunning: boolean; timers: Timer[]; }; type TimersContextValue = TimersState & { addTimer: (timerData: Timer) => void; startTimers: () => void; stopTimers: () => void; }; const TimersContext = createContext(null); 초기에는 null값이 들어감 그래서 (null) Header컴포넌트에서 TimersContext에 접근 접근할 때는 v.. # 58 Form 래퍼 컴포넌트 타입지정 import { type ComponentPropsWithoutRef } from "react"; type FormProps = ComponentPropsWithoutRef; const Form = (props: FormProps) => { return {props.children}; }; export default Form; 이것은 정상작동된다 . 그러나 button을 children으로 넣어주었을 때 button을 클릭시 submit하는 액션이 동작하도록 하고 싶다. const Form = (props: FormProps) => { const handleSubmit = (e: FormEvent) => { e.preventDefault(); const data = new FormData(e.curren.. #57 forwardRef의 타입지정 forwardRef의 타입지정 ComponentPropsWithRef로 변경 type InputProps = { label: string; id: string; } & ComponentPropsWithRef; 에러 forwardRef 활용하라는 의미 해결방법 : 리액트 함수 forwardRef 로 감싸고 ref를 매개변수로 받기 type InputProps = { label: string; id: string; } & ComponentPropsWithRef; const Input = forwardRef(({ label, id, ...props }: InputProps, ref) => { return ( {label} ); }); export default Input; 에러 : forwardRef는 unk.. # 54 polymorphic component 만들기 : Container ElementType 컴포넌트의 유효한 indentifier여야 함 as라는 속성으로 받아온 엘리먼트 식별자를 Container로 만들어 줌 as는 타입이 ElementType import { ElementType } from "react"; type ContainerProps = { as: ElementType; }; const Container = ({ as: Component }: ContainerProps) => { return ; }; export default Container; Click Me Children 받아오기 import { type ReactNode, type ElementType } from "react"; type ContainerProps = { as: ElementType;.. # 50 타입의 다양한 활용 유니언 타입, ComponentPropsWithoutRef, Button컴포넌트 유니언 타입 1. 프로퍼티를 union타입으로 구성 mode 속성을 해당 타입으로만 지정할 수 있게 만듦 2. 옵셔널 프로퍼티 props로 severity를 넣을 수도 있고 안넣을 수도 있게 구성 import { type ReactNode } from "react"; type InfoBoxProps = { mode: "hint" | "warning"; severity?: "low" | "medium" | "high"; children: ReactNode; }; const InfoBox = ({ children, mode, severity }: InfoBoxProps) => { if (mode === "hint") { return ( {children} ); } return ( Warning {child.. 이전 1 2 3 4 다음