비구조화 할당 문법을 통해 props 내부 값 추출하기 - Typescript

  • 앞선 문법에서는 props를 그대로 사용했습니다.

  • 이번에는 함수 내부에서 변수에 할당 하여 사용 할 것 입니다.

먼저 알아야 할 것!

  • props 로 오는 값은 Object의 형태를 띄고 있습니다.

Example

// App.tsx에서 name, children 값을 보내 왔다고 가정하겠습니다.
props = {
    name : 'Gong',
    children : 'React'
}
// name : string, children : string 인 것을 알 수 있습니다.
// 따라서,

interface PropFace{
    name : string;
    children : string;
}
// props로 오는 name 그리고 children은 둘 다 string이란 것을 지정해 줍니다.

할당 방식 1

MyComponent.tsx

// (...)

interface PropFace{
    name : string;
    children : string;
}

const MyComponent = (props : PropFace) => {
    const {name, children} = props;
    // const {name, children} : PropFace = props; 
    // 나중에는 이 방식도 많이 쓸 거에요!
    return(
        <div>
            Hello, My name is { name } <br/>
            The value, children is { children }!
        </div>
    );
};

MyComponent.defaultProps = {
    name : 'default Name'
};

export default MyComponent;

할당 방식 2

MyComponent.tsx

// (...)

interface propFace{
    name : string;
    children : string;
}

const MyComponent = ({ name, children } : propFace) => {
    return(
        <div>
            (...)
        </div>
    )
}
  • 변수를 받는 과정에서, interface를 사용할 수 있습니다ㅣ

  • name , children의 값을 바로 지정하고 사용 할 수 있습니다.

  • 할당 방식 중 마음에 드는 방식을 선택 하시면 됩니다.

propTypes를 통한 props 검증! - Typescript

  • Typescript 라서 굳이 필요가 없습니다..

  • interface , as string 이런 문법을 사용하여 쉽게 대체가 가능합니다.


클래스형 컴포넌트에서 props 사용하기

  • 클래스형 컴포넌트에서는 this.props 를 조회하면 됩니다.

  • 먼저, 클래스형 컴포넌트에서는 props를 적용하는 방식이 다릅니다.

Example

import {Component} from 'react';

interface propFace{
    name : string;
    favoriteNumber : number;
    children : string;
}

// Component 에 prop 부분에 propFace 적용
class MyComponent extends Component<propFace> {
    // (...)
};

export default MyComponent;
  • Component 에는 두 가지 인터페이스를 적용 할 수 있습니다.

  • Component<props, state> 로, props 그리고 state 의 타입을 지정 할 수 있습니다.

  • 만약, state만 지정 하려고 한다면, Component<undefined, stateFace> 하면 됩니다.

결과물

MyComponent.tsx

// (...) // 항상 import React from 'react'가 들어갑니다.
import { Component } from 'react';

interface PropFace{
    name : string;
    favoriteNumber : number;
    children : string;
}

class MyComponent extends Component<PropFace> {
    static defaultProps = {
        name : 'default name'
    };

    render() {
        const { name, favoriteNumber, children } = this.props;
        return (
            <div>
                Hello, My name is { name }. <br />
                The value, children is { children }. <br/>
                My favorite Number is { favoriteNumber }.
            </div>
        );
    };
};

/*
MyComponent.defaultProps = {
    name : 'default name'
}
// class 내부에 static으로 넣어주었습니다.
*/
export default MyComponent;