Typescript #3 react-Declaration function

TaejoonPark·2022년 4월 2일
0

Typescript

목록 보기
3/5

Arrow function

import React from 'react';

type GreetingsProps = {
	name: string;
}

const Greetings : React.FC<GreetingsProps> = ({name}) => {
	return <p>{name}</p>
}

Arrow function을 사용했을 때 장점

props에 children이 이미 들어가있다. type alias에서 따로 children을 선언해주지 않아도 사용할 수 있다. 아래처럼!

import React from 'react';

type GreetingsProps = {
	name: string;
  	// children: React.ReactNode // 이미 탑재되어 있음!
}

const Greetings : React.FC<GreetingsProps> = ({name, children}) => {
	return (
      <p>hello {name}</p>
      {children}
    )
}

Arrow function을 사용했을 때 단점

defaultProps를 사용해서 기본값을 설정해줄 수 없다. 근데 이부분은 props를 구조분해할당하는 부분에서 기본값 정해주면 된다.

import React from 'react';

type GreetingsProps = {
  name: string;
  mark?: string; // 👏 물음표를 붙여줬기 때문에 해당 컴포넌트를 쓰는 부분에서 props로 mark를 주지 않아도 된다.
};

const Greetings: React.FC<GreetingsProps> = ({ name, mark = '!' }) => {
  return (
    <p>
      hello {name} {mark}
    </p>
  );
};

export default Greetings;

arrow function 말고 일반 function 키워드로 defaultProps를 사용하면 정상동작한다.

function 키워드로 arrow function에서 안되는 defaultProps 사용하기

import React from 'react';

type GreetingsProps = {
  name: string;
  mark: string; // 👏 물음표를 function키워드에서는 붙여주지 않아도 된다.
  children?: React.ReactNode // 👏 만약 children을 사용한다면 설정을 해줘야 함!
};

function Greetings({ name, mark, children }: GreetingsProps) {
  return (
    <p>
      hello {name} {mark}
    </p>
  );
}

Greetings.defaultProps = {
  mark: '!',
};

export default Greetings;

function 키워드를 사용하면 children을 별도로 설정해줘야 한다. 하지만, 컴포넌트마다 children이 있는 컴포넌트도 있고 없는 컴포넌트도 있는데 Arrow Function 에서 React.FC를 사용할 때는 반드시 children이 들어가 있었다. 이는 불편한 점이 될 수도 있다!
🧑🏼‍💻 결론 : 나는 선택적으로 children을 사용할 수 있는 function키워드를 사용해야 겠다.

함수 이벤트 전달하기(function 키워드)

App.tsx

import React from 'react';
import Greetings from './Greetings';

function App() {
  const OnClickGreeting = (name: string) => {
    console.log(`hi ${name}`);
  };
  return (
    <div className='App'>
      <Greetings name='taejoon' onClick={OnClickGreeting} />
    </div>
  );
}

export default App;

Greetings.tsx

import React from 'react';

type GreetingsProps = {
  name: string;
  mark: string;
  onClick: (name: string) => void;
};

function Greetings({ name, mark, onClick }: GreetingsProps) {
  const handleClick = () => {
    onClick(name);
  };

  return (
    <>
      <p>
        hello {name} {mark}
      </p>
      <button onClick={handleClick}>hi</button>
    </>
  );
}

Greetings.defaultProps = {
  mark: '!',
};

export default Greetings;

정리

리액트에서는 arrow function보다 function키워드를!

여러 장점을 보았을 때 리액트에서는 화살표 함수보다 function키워드를 사용하는 편이 더 낫겠다. 모양새가 function키워드와 arrow function을 같이쓴다는 점이 좀 그렇기는 하지만 컴포넌트를 정의할 때만 function키워드를 사용하는 모양새다보니 나름 괜찮은 것 같기도 하다. 실제 강의에서도 섞어 쓰는 모습을 보니 괜찮을 것 같다.

  • children을 선택적으로 설정할 수 있다는 것!
  • defaultProps를 정상적으로 사용할 수 있다는 것!

리액트에서 타입스크립트를 쓰면서 얻는 장점

개발 자체가 좀 편해진다! 컴포넌트를 사용할 때 실수로 props를 빠트렸다면 마우스를 hover시켜서 뭘 넣어야 하는지 알 수 있다. 아니면 ctrl + space만 써도 어떤 props를 넣어야 되고 어떤 타입을 넣어야되는지 알려준다.

profile
공유하는 것을 좋아하는 프론트엔드 개발자

0개의 댓글