근황 & 실전 TypeScript 1

2021. 7. 1. 22:32프로그래밍/Typescript

728x90

벌써 7월이다. 종강을하고 벌써 2주가 지났다.
하지만 참 시간을 열심히 쓰고 있다.
운동도 꼬박꼬박 가고 있고, 스터디카페도 규칙적으로 가기 시작했다.
특히 이번주는 오전 운동, 오후 스터디카페의 패턴이 몸에 익기 시작했다.

사실 그동안 사업 기획 및 개발에 정신없이 시간을 보냈다.
TypeScript Handbook 정리도 끝났겠다, 실전으로 코딩을 하면서 부딪히고 있다.
근데 참 이게 쓰면쓸수록 어려운거 같기도 하고...
논리적으로 어려운게 아니라 이게 되나? 싶은 미지의 영역이 있다.

아무튼 그래서 이제는 TypeScript로 짠 코드를 보며 잡기술을 하나씩 써볼까한다.

프로젝트는 React.js + Material-ui + TypeScript로 구성되어있다.


코드 살펴보기

// SurveyPage.tsx
import { WeightSurvey, ScreenSizeSurvey, BrandSurvey, BudgetSurvey, HelpSurvey } from '../components/survey';

const SurveyPage:React.FunctionComponent<...> = ({ ... }) => {

  ...

  return (
    <div>
      {state >= 0 && [
        WeightSurvey,
        ScreenSizeSurvey,
        BrandSurvey,
        BudgetSurvey,
        HelpSurvey,
      ][state]({ survey: question, onNext: handleNext })}
    </div>
  );
}

이 코드는 SurveyPage라는 React Hook으로 짠 코드의 일부분이다.

설명을 하자면, state의 변화에 따라서 5개의 컴포턴트중에 하나를 출력하는 방식이다.

간단해보이지만 여기에는 세가지 잡기술의 컴비네이션(덴경대 소리질러~)이 있다.

하나하나씩 살펴보자.


1. index.js로 폴더의 모듈들을 export하자!

이거는 TypeScript나 React의 기술은 아니고, Javascript의 기본적인 기능 중에 하나이다.

첫번째 줄을 살펴보자

import { WeightSurvey, ScreenSizeSurvey, BrandSurvey, BudgetSurvey, HelpSurvey } from '../components/survey';

자, 여기서 '../components/survey'는 파일이 아니라 폴더이다.

엥? 폴더를 import한다고? 그럼 뭘 어떻게 import하는거지?

폴더를 import하면 그 폴더의 index.js를 불러온다.
'components/survey/index.js'를 살펴보자.

// index.tsx
import BrandSurvey from './BrandSurvey';
import BudgetSurvey from './BudgetSurvey';
import HelpSurvey from './HelpSurvey';
import ScreenSizeSurvey from './ScreenSizeSurvey';
import WeightSurvey from './WeightSurvey';

export {
  BrandSurvey,
  BudgetSurvey,
  HelpSurvey,
  ScreenSizeSurvey,
  WeightSurvey,
};

보다시피 같은 폴더에 있는 5개의 모듈을 import한 뒤, Object의 형태로 export하였다.

Material UI나 React 컴포넌트를 import할 때 사용하는 코드들도 보통 이런 식이다.

import { FormControl, InputLabel, Select } from '@material-ui/core';

한 폴더 내의 여러개의 모듈을 import하고 싶다면 다음과 같이 해보자!


2. 배열 형식을 이용하여 컴포넌트를 관리해보자!

React를 하다보면, state에 따라서 컴포넌트를 출력하고 싶을 때가 있다.

내 프로젝트의 경우에는 state에 따라 다양한 형태의 페이지를 출력해야 하는데,
그러려면 여러 모듈을 import하는 식으로 해야한다.
가장 단순한 방식은 이렇게 할 수 있겠다.

import { WeightSurvey, ScreenSizeSurvey, BrandSurvey, BudgetSurvey, HelpSurvey } from '../components/survey';

const ~~ = (props) => {
  ...
  
  return (
  	<div>
      {state == 0 && <WeightSurvey survey={question} onNext={handleNext} />}
      {state == 1 && <ScreenSizeSurvey survey={question} onNext={handleNext} />}
      {state == 2 && <BrandSurvey survey={question} onNext={handleNext} />}
      {state == 3 && <BudgetSurvey survey={question} onNext={handleNext} />}
      {state == 4 && <HelpSurvey survey={question} onNext={handleNext} />}
    </div>
  )
}

 와! 샌즈! 사수가 코드리뷰하다가 커피를 집어던져도 할 말이 없는 코드다.

React가 워낙 '모르면 맞아'식의 모르면 답도 없는 내용이 많다.
우리가 여기서 생각해 봐야할 내용은, 이 노드(엘리먼트, <>로 표현되는 것)도 하나의 객체의 처리를 받는다는 것이다.
그냥 하나의 변수라고 생각하면 된다.

변수들은 하나의 배열에 넣을 수 있다! 그럼 배열에 넣어보자.

import { WeightSurvey, ScreenSizeSurvey, BrandSurvey, BudgetSurvey, HelpSurvey } from '../components/survey';

const ~~ = (props) => {
  ...
  
  return (
    <div>
      {[<WeightSurvey survey={question} onNext={handleNext} />}
        <ScreenSizeSurvey survey={question} onNext={handleNext} />}
        <BrandSurvey survey={question} onNext={handleNext} />}
        <BudgetSurvey survey={question} onNext={handleNext} />}
        <HelpSurvey survey={question} onNext={handleNext} />
      ][state]}
    </div>
  )
}

와 ^____^ 너무 깔끔하고 좋다.

하지만 여기서 문제점은, survey와 onNext가 똑같은게 반복이 된다는것이다.

내가 계획한 질문이 20개정도 되는데, 저걸 복사 붙여넣기로 20줄을 넣으면 정신이 아찔해질 것이다.

그것에 대한 해결책은 다음 잡기술에 있다.


3. 함수형 호출

우선 알아야 할 부분은, React Node의 형태다.

// 함수형 React Node
function ComponentA(props):React.FunctionComponent {
  return <></>;
}

// 화살표 함수형 React Node
const ComponentB:React.FunctionComponent = (props) => {
  return <></>;
}

// 클래스형 React Node
class ComponentC extends React.Component {
  render() {
    // this.props
  
    return <></>;
  }
}

이런 식으로 모듈을 만들어서 다음과 같이 사용한다.

const a = 1;
const b = 2;

<Component1 a={a} b={b} />

자, React Node의 원형을 살펴보자.

ComponentA는 함수다. 
props를 매개변수로 받는 함수다. 즉, 함수의 형태로 호출이 가능 한 것이다.

ComponentA({a, b});

그리고 이렇게 반환된 값은 React.FunctionComponent의 형태를 가지는 객체가 된다.

이걸 render하면 우리가 아는 html이 형태로 나오게 되는 것이다.

이걸 이용하여 코드를 바꿔보자.

  {[
    WeightSurvey,
    ScreenSizeSurvey,
    BrandSurvey,
    BudgetSurvey,
    HelpSurvey,
  ][state]({ survey: question, onNext: handleNext })}

알기 쉽게 순서별로 살펴보자.

{[
  WeightSurvey,
  ScreenSizeSurvey,
  BrandSurvey,
  BudgetSurvey,
  HelpSurvey,
][state]({ survey: question, onNext: handleNext })}

||
||   state가 0일 때
\/

{WeightSurvey({ survey: question, onNext: handleNext })}

||
\/

<WeightSurvey survey={question} onNext={handleNext} />

'프로그래밍 > Typescript' 카테고리의 다른 글

실전 TypeScript - 4  (0) 2021.07.04
실전 TypeScript 2  (0) 2021.07.02
TypeScript - Handbook (Modules)  (0) 2021.06.23
TypeScript - Handbook(Classes)  (0) 2021.06.22
TypeScript - HandBook(Object Types)  (0) 2021.06.08