[리액트] React with Typescript

김학재·2021년 9월 11일
0

리액트

목록 보기
5/8
post-thumbnail

cra with typescript

npx create-react-app "프로젝트명" --template typescript

tsx

Typescript file writtern using JSX syntax

tsx 파일 만들어보기

// Textfield.tsx
import React from 'react'

interface Person {
  firstName: string;
  lastName: string;
}

interface Props {
  text: string;
  ok?: boolean;
  i?: number;
  fn?: (bob: string) => string;
  person: Person;
}

const Textfield: React.FC<Props> = () => {
  return (
    <div>
      <input />
    </div>
  )
}

export default Textfield

React.FC : 해당 컴포넌트가 리액트의 함수형 컴포넌트라는 것을 명시

Typescript 사용시 React.FC 주의

The better way to type react components
함수 선언식으로 컴포넌트를 만들면 React.FC는 사용할 수 없고 대신 props를 interface로 넘겨주는 방식으로 체크하게 된다.
함수 선언은 바디가 호이스트되지만, 함수 표현식은 호이스트되지 않는다.
또한 직접, props의 입력을 통해 오류를 방지할 수 있다.

useState with typescript

// ...

interface TextNode {
  text: string
}

const Textfield: React.FC<Props> = () => {
  const [count, setCount] = useState<TextNode>({ text: 'hello'})
  
  setCount({text: 'test'})

  // ...
}

useRef with typescript

// ...

const inputRef = useRef<HTMLInputElement>(null)
const divRef = useRef<HTMLDivElement>(null)

return (
  <div ref={divRef}>
    <input ref={inputRef}/>
  </div>
)

어떤 타입이어야 할 지 잘 모를 때는 마우스 호버 시에 힌트가 뜬다.

useReducer with typescript

시작하기 전 useReducer란

reducer는 현재 상태와 액션 객체를 파라미터로 받아와서 새로운 상태를 반환해주는 함수.

function reducer(state, action) {
  // 새로운 상태를 만드는 로직
  // const nextState = ...
  return nextState;
}

reducer에서 반환하는 상태는 곧 컴포넌트가 지닐 새로운 상태

useReducer의 사용법

const [state, dispatch] = useReducer(reducer, initialState);

state는 우리가 앞으로 컴포넌트에서 사용할 수 있는 상태, dispatch는 액션을 발생시키는 함수


typescript와 같이 사용을 위해서는 state와 action의 type을 정의해주면 된다. 자세한 내용은 코드 참고

profile
YOU ARE BREATHTAKING

0개의 댓글