aotoyae

[TS/React] props 유연하게 내리기 & Event Handler 본문

TypeScript

[TS/React] props 유연하게 내리기 & Event Handler

aotoyae 2024. 3. 6. 15:16

 

 

💡 프롭스를 더 유연하게 내려보자 ~

 

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}</>;
};

<P == unKnown> 이라서 ~

 

🙋‍♂️ 다음은 다섯 개 중 네 개의 타입을 받아오고 있는 프로필
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 에 함수를 넣어보면 된다!

 

뭔가 뜨고있다. 그대로 가져와 increment 에 넣어준다.

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 에 호버. 얘가 이벤트 핸들러다.
e 에 호버. 얘는 걍 이벤트

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;