Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 리액트
- 리액트 공식문서
- JavaScript
- 한글 공부 사이트
- 내일배움캠프 최종 프로젝트
- REACT
- React Hooks
- 타입스크립트 props
- 파이썬 slice
- 파이썬 replace
- 내일배움캠프 프로젝트
- 파이썬 for
- typeScript
- 코딩테스트
- 리액트 프로젝트
- useState
- 파이썬 for in
- 프로그래머스
- Next 팀 프로젝트
- 타입스크립트 리액트
- 파이썬 enumerate
- useEffect
- 타입스크립트
- tanstack query
- 파이썬 반복문
- 파이썬 딕셔너리
- 내배캠 프로젝트
- 내일배움캠프
- 리액트 훅
- 자바스크립트
Archives
- Today
- Total
sohyeon kim
[TS/React] props 유연하게 내리기 & Event Handler 본문
728x90
💡 프롭스를 더 유연하게 내려보자 ~
UtilityType.tsx
import {
AddressComponent,
PersonChildComponent,
ProfileComponent,
} from "./UtilityTypeChildren";
export type PersonProps = {
id: string;
description: string;
address: string;
age: number;
profile: string;
};
export const PersonComponent = ({ // ❗️ 다섯가지 타입들 설정
id,
description,
address,
age,
profile,
}: PersonProps) => {
return (
<>
<PersonChildComponent>
<div>{id}</div>
</PersonChildComponent>
<ProfileComponent // ❗️ 네개 내려주는 중
description={description}
address={address}
age={age}
profile={profile}
/>
<AddressComponent address={address} /> // ❗️ 어드레스만 하나 내려주는 중
</>
);
};
UtilityTypeChildren.tsx
import { ReactNode } from 'react';
export const PersonChildComponent = ({ // ❗️ 여긴 칠드런이 필요하고
children,
}: {
children?: ReactNode; // ❗️ 지금 옵셔널하게 받는 중
}) => {
return <>{children}</>;
};
export const ProfileComponent = ({ // ❗️ 여긴 네 가지 타입이
description,
address,
age,
profile,
}: {
description: string;
address: string;
age: number;
profile: string;
}) => {
return <></>;
};
// ❗️ 여긴 어드레스만 필요하다.
export const AddressComponent = ({ address }: { address: string }) => {
return <></>;
};
🤤 칠드런 파일에서 props 타입을 다르게 작성해 보자.
🙋♂️ 우선 옵셔널 하게 받고 있는 칠드런!
PropsWithChildren 으로 바꿀 수 있다.
참고로 얘는 제네릭을 안 써도 괜찮다.
export const PersonChildComponent = ({ children }: PropsWithChildren) => {
return <>{children}</>;
};
🙋♂️ 다음은 다섯 개 중 네 개의 타입을 받아오고 있는 프로필
Omit 을 활용하자.
PersonProps 타입을 사용하지만 'id' 만 제외하겠다는 것~
export const ProfileComponent = ({
description,
address,
age,
profile,
}: Omit<PersonProps, 'id'>) => {
return <></>;
};
만든 Omit 타입을 변수처럼 따로 빼 사용할 수 있다!
type OmitIdType = Omit<PersonProps, 'id'>;
export const ProfileComponent = ({
description,
address,
age,
profile,
}: OmitIdType) => {
return <></>;
};
🙋♂️ 이제 한 가지 타입만 받아오고 있는 어드레스
Pick 을 활용하자.
type PickAddressType = Pick<PersonProps, 'address'>;
export const AddressComponent = ({ address }: PickAddressType) => {
return <></>;
};
// 여러개를 픽하고싶다면 아래처럼 작성
type PickAddressType = Pick<PersonProps, 'address' | 'id'>;
💡 이벤트 핸들러에 타입스크립트를 사용해 보자.
import { useState } from 'react';
function App() {
const [counter, setCounter] = useState<number>(1);
const increment = () => {
setCounter((prev) => prev++);
};
return <div onClick={increment}>{counter}</div>;
}
export default App;
여기서 만약 아래처럼 e 를 받아오는 함수라면
타입을 정해 달라는 메세지가 뜬다.
어떤 타입을 넣어야 하는지 어떻게 알 수 있을까?!
👀 onClick 에 함수를 넣어보면 된다!
function App() {
const [counter, setCounter] = useState<number>(1);
const increment = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e.target;
};
return <div onClick={increment}>{counter}</div>;
}
🙋♂️ 더 간단하게 써보자.
onClick 에 호버를 해보니 MouseEventHandler 라는게 써있고,
우린 위 함수에 MouseEvent 를 써주고 있다.
onChange 를 한번 써보니 FormEventHandler 가 써있다.
그러니 인자 타입엔 FormEvent 가 들어가는 것!
그리고 이 이벤트를 사용하고 있는 컴포넌트 div ! 를 제네릭에 넣어주고 있다.
그래서 이렇게 써줄 수 있다는 ~
import { MouseEvent, useState } from 'react'; // 마우스이벤트 리액트에서 불러옴
function App() {
const [counter, setCounter] = useState<number>(1);
const increment = (e: MouseEvent<HTMLDivElement>) => {
e.target;
};
return <div onClick={increment}>{counter}</div>;
}
export default App;
이렇게나 ~
import { useState } from "react";
function App() {
const [counter, setCounter] = useState<number>(1);
const eventHandler = (e: React.MouseEvent<HTMLDivElement>) => {};
return <div onClick={eventHandler}>{counter}</div>;
}
export default App;
728x90
반응형
'TypeScript' 카테고리의 다른 글
[TS/React] Create React App, JS ➡️ TS 변경 (1) | 2024.03.07 |
---|---|
[TS/React] 타입스크립트로 리액트 vite 시작하기, JS ➡️ TS 변경 (1) | 2024.03.06 |
[TS/React] TodoList 에 활용, props & children props (1) | 2024.03.06 |
[TS] 비동기 함수 & React에 타입스크립트 사용 : props (1) | 2024.03.06 |
[TS] 타입스크립트 활용 : 간단한 책 대여 프로그램 class (1) | 2024.03.06 |