본문 바로가기

TypeScript

TypeScript with React

반응형

1. setState가 props로 전달될 때

import React, { Dispatch, SetStateAction } from 'react';

type ChildProps = {
  setCount: Dispatch<SetStateAction<number>>;
};

function Child({ setCount }: ChildProps) {
  return <button onClick={() => setCount(prev => prev + 1)}>증가</button>;
}

 

2. useRef 타입 지정

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef<HTMLInputElement>(null);

  return <input label="이름" ref={inputRef} />;
}

 

두 가지 방법이 있습니다

 

첫 번째, forwardRef를 사용하여 ref 전달하기

 

import React, { forwardRef } from 'react';

const Child = forwardRef<HTMLInputElement, { label: string }>((props, ref) => {
  return (
    <div>
      <label>{props.label}</label>
      <input ref={ref} />
    </div>
  );
});

 

두 번째, ref를 props로 전달하기

import React, { useRef } from 'react';

// 자식 컴포넌트에서 ref를 props로 받음
type ChildProps = {
  ref: React.RefObject<HTMLInputElement>;
};

function Child({ ref }: ChildProps) {
  return <input ref={ref} />;
}

 

 

3. children 타입

import React, { ReactNode } from 'react';

type Props = {
  children: ReactNode;
};

function Layout({ children }: Props) {
  return <div>{children}</div>;
}

 

4. 이벤트 핸들러 타입

클릭 이벤트

import React, { MouseEvent } from 'react';

function Button() {
  const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
    console.log(e.currentTarget);
  };

  return <button onClick={handleClick}>클릭</button>;
}

 

인풋 변경 이벤트 

import React, { useState, ChangeEvent } from 'react';

function InputField() {
  const [value, setValue] = useState('');

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  return <input value={value} onChange={handleChange} />;
}

 

5. 폼 제출 이벤트 타입

import React, { FormEvent } from 'react';

function FormExample() {
  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">제출</button>
    </form>
  );
}

 

6. 커스텀 훅 반환 타입

import React, { useState } from 'react';

function useToggle(initial: boolean): [boolean, () => void] {
  const [state, setState] = useState(initial);
  const toggle = () => setState(prev => !prev);
  return [state, toggle];
}
반응형

'TypeScript' 카테고리의 다른 글

고급 TypeScript 문법  (0) 2025.04.26
type 과 interface의 차이  (0) 2025.04.25