타입스크립트 리액트 컴포넌트 만들어보기

nevermind·2022년 10월 18일
0

typescript

목록 보기
3/12

출처: https://react.vlpt.us/using-typescript/02-ts-react-basic.html

🙈실습

  • CRA를 통해 컴포넌트 쉽게 만들어보기 $ npx create-react-app ts-react-tutorial --template typescript

  • src/Greeting.tsx

import React from 'react'

type GreetingProps = {
    name: string;
    mark: string;
    optional?: string;
    onClick: (name: string) => void
}
const Greeting = ({ name, mark, onClick }: GreetingProps) => {
    const handleClick = () => onClick(name);

    return (
        <div>
            <div>안녕 {name} {mark}</div>
            <button onClick={handleClick}>Click</button>
        </div>
    )
}

Greeting.defaultProps = {
    mark: '!'
}

export default Greeting
  • src/App.tsx
import React from 'react';
import Greeting from './Greeting';


function App() {
  const onClick = (name: string) => {
    console.log(name)
  }
  return (
    <Greeting name='리액트' onClick={onClick} />
  );
}

export default App;

React.FC와 함수형 차이

  • React.FC 사용시
    - 👍
    - props에 기본적으로 children이 들어가있음
    - 컴포넌트의 defaultProps, propTypes, contextTypes 를 설정 할 때 자동완성이 될 수 있다는 것
    - 👎
    - 컴포넌트에 따라 children이 들어가면 안되는 경우에 대한 처리 못함
    - defaultProps 가 제대로 작동하지 않는다

리액트 상태관리하기

  • useState : useState를 사용할 때는 제너릭을 사용하지 않아도 알아서 타입을 유추하기에 생략가능!
    - 상태가 null일 수도 있고 아닐수도 있을때 Generics 를 활용하시면 좋음!
type Information = { name: string; description: string };
const [info, setInformation] = useState<Information | null>(null);
  • input 상태관리(이벤트)
    - 이벤트 타입은 onChange에 마우스를 올리면 알 수 있다.
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm({
      ...form,
      [name]: value
    });
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    onSubmit(form);
    setForm({
      name: '',
      description: ''
    });
  };
    return (
        <form onSubmit={handleSubmit}>
            <input name="name" value={name} onChange={onChange} />
            <input name="desc" value={desc} onChange={onChange} />
            <button type="submit">등록</button>
        </form>
    )

출처: https://yceffort.kr/2022/03/dont-use-react-fc

profile
winwin

0개의 댓글