-
[포스코x코딩온] TypeScript with React[포스코x코딩온] 웹개발자 풀스택 부트캠프8기 2023. 10. 10. 18:43728x90
TypeScript with React
- 프로젝트 만들기
npx create-react-app 프로젝트 이름 --template typescript
//기존 프로젝트에 typescript를 적용한다면 npm install typescript @types/node @types/react @types/react-dom @types/jest //1. 모듈 설치 //2. js & jsx 파일을 ts, tsx 파일로 변경 //3. tsconfig.json 파일
예시 코드
import React, { useState, useRef } from "react"; //?는 선택이다.(있으면 넣고 없으면 안넣는다.) //만약 ?을 안하면 무조건 값이 있어야 한다.(아니면 오류 발생) // | Union 타입은 둘 다 적용을 할 수 있다. interface Props { name: string | number; age?: number; } //방법1. //FC: Function Component의 약자 const PropsType1: React.FC<Props> = ({ name, age }) => { const [count, setCount] = useState<number>(0); const myInput = useRef<HTMLInputElement>(null); const handleFocus = () => { //!는 값이 무조건 있을 때 사용. myInput.current!.focus(); }; const onClick = (e: React.MouseEvent<HTMLElement>) => {}; //React.MouseEvent<HTMLElement> => 찾기 어렵고 귀찮으면 any를...ㅎㅎ return ( <> <h2>Hello {name}</h2> <h4>{age}</h4> <input ref={myInput} /> <button onClick={handleFocus}>버튼</button> <form action=""> <button onClick={(e) => onClick(e)}>제출</button> </form> </> ); }; export default PropsType1; //방법2. // export default function PropsType1({ name }: Props) { // return ( // <> // <h2>Hello {name}</h2> // </> // ); // }
props와 interface
- props를 이용해서 데이터를 상위 컴포넌트에서 받을 때는 props가 어떤 형태로 넘어오는지 미리 type을 적어야 한다.
interface Props{ name: string; } function PropsType1({name}: Props){ return( <> <h2>Hello {name} </h2> </> ); }
- 상위 컴포넌트에서 props를 넘겨줄 때, 정의된 props라면 반드시 넘겨줘야 한다.
- 하위 컴포넌트에서 interface로 정의된 props들은 사용하지 않더라도 넘겨주어야 한다.
- 넘겨주고 싶지 않은 props가 있다면 '?'를 이용한다.
useState generic <T>
- generic 함께 쓰기
- 초기값에 대한 type을 generic을 이용해서 설정
- setState를 이용해서 state를 변경할 때도 generic으로 정해준 type으로만 변경이 가능하다.
const [count, setCount] = useState<number>(0); const [text, setText] = useState<string>('');
- but, typescript가 타입 유추를 알아서 하기에 generic을 쓰지 않아도 괜찮다.
- state의 값이 null 일 수도 있고 아닐 수 도 있을 때는 반드시 generic으로 union type을 전달해야 한다.
- 값 저장
- 초기값에 대한 type을 generic으로 작성
- const refVal = useRef<number>(0);
- DOM 접근
- DOM 객체에 접근하기 위한 useRef의 generic에는 type에 HTMLElement 타입 이용
- const ref = useRef<HTMLInputElement>(null);
event 객체의 type
- html 요소에 이벤트를 적용할 때, 이벤트가 발생한 요소에 대한 정보가 담겨 있는 객체
<div onClick= {(e) => console.log(e)}>onClick</div>
- onClick, onDrag, ...(Click 과 관련된 event 객체)
- React.MouseEvent<HTMLElement>
- onChange
- React.ChangeEvent<HTMLInputElement>
- onKeydown, onKeyup,...(keyboard 이벤트와 관련된 event 객체)
- React.KeyboardEvent<HTMLInputElement>
728x90'[포스코x코딩온] 웹개발자 풀스택 부트캠프8기' 카테고리의 다른 글
[포스코x코딩온] JAVA 기초(식별자, 데이터 타입, 입출력,조건문, 메소드, 반복문) (0) 2023.10.20 [포스코x코딩온] JAVA의 시작(개발환경 구축) (0) 2023.10.19 [포스코x코딩온] TypeScript 기초 (1) 2023.10.10 [포스코x코딩온] React- Redux/ Redux-Toolkit (1) 2023.10.09 [포스코x코딩온] React- Context API / createContext (0) 2023.10.04