티스토리 뷰

카테고리 없음

React component 타입

철철22 2018. 8. 28. 10:56
반응형

함수형의 stateless component

클래스 형태의 statefull component

Redux 가 연결된 container component 가 있다

 

1. stateless component

 

React는 Props의 데이터형을 설정하기 위해 컴포넌트 클래스는 static 타입의 PropTypes 변수 안에 타입을 선언하는 방식을 사용한다. 

하지만 이제는 TypeScript를 사용하므로 interface나 type을 사용해서 Props의 형태를 선언하면 된다.

import * as React from 'react'

type Props = {} // Props 타입 선언

// 컴포너트의 리턴 타입을 Props 타입과 함께 설정
const TSSFC: React.SFC<Props> = props => {
  const { children, ...restProps } = props
return <div {...restProps}>{children}</div>
}
export default TSSFC

React의 Props와 State의 타입 선언에는 generic 타입을 사용한다.


 generic 타입은 함수처럼 인자를 받아서 타입 선언을 유동적으로 바꿀 수 있으므로 컴포넌트마다 서로 다른 Props와 State를 선언하는데 활용된다.


컴포넌트 TSSFC의 리턴 타입이 React.SFC<Props>으로 되어 있는데, 이는 Props라는 타입을 전달받아서 내부적으로 타입 선언에 사용한다는 의미이다.




2. statefull component


import * as React from 'react'
type Props = {}
type State = {}
class TSComponent extends React.Component<Props, State> {
  static defaultProps = {}
state: State = {}
constructor(props: Props) {
    super(props)
  }
render() {
    return <div>TSComponent</div>
  }
}
export default TSComponent

클래스 컴포넌트는 React.Component 대신 React.Component<Props, State>를 상속받는 방식을 사용해서 타입을 추가한다. 

그리고 클래스 내부에서 state 변수를 선언할 때 타입을 붙여주고 constructor 함수의 인자에도 타입을 붙여준다. 

이 외에는 Javascript의 React 컴포넌트와 차이가 없다.

오히려 PropTypes를 이용한 타입 선언보다 TypeScript의 타입 선언이 더 간단하기 때문에 더 간결하게 느껴질 수 있다.


3. container component


import * as React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators, compose, Dispatch } from 'redux'
import { RootState } from '../../store/rootReducer'
import todoActions from '../../store/todo/actions'
import { returntypeof } from 'react-redux-typescript'


const mapStateToProps = (state: RootState) => ({
  todoList: state.todo.list,
})

const mapDispatchToProps = (dispatch: Dispatch<{}>) =>
  bindActionCreators(
    {
      addTodo: todoActions.addTodo,
    },
    dispatch
  )
// 두 함수에 의해 생성될 Props를 객체 형태로 가져온다.
const statePropTypes = returntypeof(mapStateToProps)
const actionPropTypes = returntypeof(mapDispatchToProps)

type Props = typeof statePropTypes & typeof actionPropTypes & {}
type State = {}
class Container extends React.Component<Props, State> {
  static defaultProps = {}
  state: State = {}
constructor(props: Props) {
    super(props)
  }
render() {
    return null
  }
}
export default compose(connect(mapStateToProps, mapDispatchToProps))(Container)

컨테이너 컴포넌트는 외부 라이브러리를 활용한다. 

 

mapStateToProps 함수와 mapDispatchToProps 함수의 리턴값을 typeof 명령어로 타입 형태로 바꿀 수 있도록 객체 형태로 바꿔주는 returntypeof라는 헬퍼 함수가 그것이다. 

 

두 함수의 리턴 타입을 직접 작성하는 것보다 자동으로 생성해주는 라이브러리를 사용함으로서 컴포넌트의 Props 타입 선언을 무척 간편하게 할 수 있다.

위의 예제 코드에서 returntypeof(mapStateToProps)의 

결과는 { todoList: state.todo.list }가 되고 이를 typeof 연산자로 타입으로 변경하면 아래와 같은 형태가 된다.


type StatePropTypes {
  todoList
:Array<Todo>, //예시를 위해 임의로todoListTodo 타입의 배열이라고 표현
}



그리고 type 키워드로 선언한 타입은 & 연산자를 통해 intersection 타입 형태로 합치는 것이 가능하므로 사용자가 직접 정의한 Props와 함께 사용할 수 있다.

 

type Props typeofstatePropTypes typeofactionPropTypes &{}

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함