[원티드] 5월 11일 TIL

eaasurmind·2022년 5월 12일
0

TIL

목록 보기
8/27

Typescript in react

예전에 타입스크립트를 배웠는데 많이 까먹어서 개인 과제 도중 자꾸 막히는 부분이 생겨 요번 기회에 다시 공부하게 되었다

state 타입 지정

지정하지 않아도 타입 추론 기능에 의거하여 알아서 하긴 한다.

const [count, setCount] = useState<number>(0);
  const onIncrease = () => setCount(count + 1);
  const onDecrease = () => setCount(count - 1);

or연산자 같은 것이 필요한 타입일 때는 제네릭이 필요해진다

type Information = { name: string; description: string };
const [info, setInformation] = useState<Information | null>(null);

Input타입

함수에 마우스를 올리면 자동으로 표시가 된다.


onChange 의 e 객체의 타입을 React.ChangeEvent<HTMLInputElement>

함수 부분은 React.FormEvent<HTMLFormElement>
  
//기본적인 form 작성 방안
  import React, { useState } from 'react';

type MyFormProps = {
  onSubmit: (form: { name: string; description: string }) => void;
};

function MyForm({ onSubmit }: MyFormProps) {
  const [form, setForm] = useState({
    name: '',
    description: ''
  });

  const { name, description } = form;

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm({
      ...form,
      [name]: value
    });
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    // 여기도 모르니까 any 로 하겠습니다.
    e.preventDefault();
    onSubmit(form);
    setForm({
      name: '',
      description: ''
    }); // 초기화
  };
  

ReactFC

처음 배울 때 배운데로 항상 reactFC를 이용해 작성했는데
곰곰히 생각해보니 필요성에 대한 의문이 들어 여러 글들을 찾아보았다.

--> 예제

interface AppProps {
  name: string;
}

const App: React.FC<AppProps> = (props) => {
  return <div>hello {props.name}</div>
}
 

FC는 단점이 존재했는데

children props를 옵셔널로 내포해 다소 혼돈을 줄 수 있는 여지가 있다

type PropsWithChildren<P> = P & { children?: ReactNode | undefined };

참고:
https://react.vlpt.us/using-typescript/03-ts-manage-state.html

profile
You only have to right once

0개의 댓글