[TypeScript] CRA 생성 및 Function과 Allow Function

손종일·2020년 12월 1일
0

TypeScript

목록 보기
3/4
post-thumbnail

TypeScript

CRA에서는 TypeScript를 지원하기 때문에 CRA TypeScript를 생성할 수 있다.

npx create-react-app [project_name] --template typescript

CRA 세팅
위의 명령어로 CRA를 생성하게 되면 App.js가 아닌 App.tsx가 생성됩니다.

Arrow Function

아래와 같이 React.FC라는 것을 사용해서 type을 지정할 수 있지만, React.FC에는 기본적으로 children이 탑재되어 있다. 그렇기 때문에 Greetings. ~ 자동완성이 되도록 사용할 수 있지만
치명적인 단점이 존재하는데 default props가 작동하지 않는다.
그러므로 인자를 받을때 직접 넣어줘야한다.
또한, children을 사용하지 않는 컴포넌트에도 사용하게되면 불필요한 children이 늘어난다는 단점이 있다.

--------------------------------------------------------------- Greetings.tsx
import React from 'react';

type GreetingsProps = {
  name: string,
  mark?: string,
}

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

export default Greetings;


--------------------------------------------------------------- App.tsx
import React from 'react';
import Greetings from './Greetings';

function App() {
  const onClick = () => {
  }

  return (
    <GreetingsProps name='AD' onClick={onClick} />
  );
}

export default App;

Function keyword Function

--------------------------------------------------------------- GreetingsFunc.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 (
    <div> Hello, {name} {mark}
      <div>
        <button onClick={handleClick}> Click me</button>
      </div>
    </div>
  )
}

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

export default Greetings;


--------------------------------------------------------------- App.tsx
import React from 'react';
import Greetings from './Greetings';

function App() {
  const onClick = () => {
  }

  return (
    <Greetings name='AD' onClick={onClick} />
  );
}

export default App;
profile
Allday

0개의 댓글