Web/TypeScript
[TypeScript] React+TypeScript 로 개발 시작하기
밍맹030
2022. 2. 16. 20:11
728x90
1. [react+typescript project 생성]
npx create-react-app [프로젝트명] --template typescript
2. 함수형 컴포넌트 작성 방법
- `type Image`와 `interface ListProps`와 같이 컴포넌트의 props 타입을 명시하여 작성한다. 이를 통해 property로 유효하지 않은 값이 전달되면 바로 오류를 확인할 수 있다.
import React from "react";
type Image = {
src: string;
};
interface ListProps {
header: string;
content: string;
image?: Image;
}
const List = ({ header, content, image }: ListProps) => {
return (
<div>
{image && <img src={image.src}/>}
<div>{header}</div>
<div>{content}</div>
</div>
);
};
3. Hook 사용법
(useEffect : 별도 타입 지정 필요 없음)
useState
초기값을 설정하는 경우라면 자동으로 타입이 지정되므로 직접 타입을 지정할 필요가 없다.
그러나 초기값을 설정할 수 없는 경우에는 아래와 같이 작성한다.
type ListObj = {
id: string;
header: string;
content : string | null;
image: string | null;
};
const [myList, setMyList] = useState<ListObj | null>(null);
- 어떤 type의 값이 오게 될 지 모르기 때문에 초기값으로 null을 지정해준다.
4. Event 처리 방법
- event의 type으로는 React의 이벤트 시스템을 사용하기 때문에 React 버전의 이벤트를 직접 지정해야한다.
아래 세 가지 예시를 보자.
-1. onChange 이벤트
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
// 함수 작성
};
-2. onSubmit 이벤트
const onClickSubmit = (e: React.FormEvent<HTMLButtonElement>) => {
event.preventDefault();
// 함수 작성
};
-3. onClick 이벤트
const onButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
// 함수 작성
};
728x90