본문 바로가기
모바일 APP/React-Native

재사용 컴포넌트 (reusable components)

by 살길바라냐 2021. 9. 15.
반응형

개발을 하다보면 
아무리 프레임워크가 좋다고 해도
기존것을 기능에 맞춰 커스텀 해야 하는 경우가 생긴다. 

 

재사용 컴포넌트란:

하나의 목적에 부합하는 것이 아니라 여러 코드에
범용적으로 적용하요 재사용 할수 있는 컴포넌트를 말한다.

그냥 합체라고 생각 하면 될듯...

 

특히 타입스크립트에서는: 

- ReactNode라는 타입,
- children이라는 속성,
- 수신하는 속성을 한꺼번에 다른 컴포넌트에 전달하는 기법이 필요하다.

 

기본사용법은 아래와 같다.

// 재사용 컴포넌트 예시

import type {FC, ReactNode} from 'react'

type SomeProps =  {
 children?: ReactNode
}

export const Some: FC<SomeProps> = ({children}) => {
	return <View>{children}</View>
}

 

// 적용 예

<View>
<Some><Image/></Some>
<Some><Text>some</Text></Some>
</View>

 

좀더 섬세하게 만들어 보자

우선 타입스크립트 대수데이터 타입을 공부하고 올 것!

import React from "react"
import type {FC, ComponentProps, StyleProp, ViewStyle} from 'react'
import {TouchableOpacity, View} from 'react-native'

// TouchableOpacityProps 속성 타입
type TouchableOpacityProps = ComponentProps<typeof TouchableOpacity>

// 교집합 타입 TouchableOpacityProps면서 ViewStyle 속성을 가지고 있는
export type TouchableViewProps = TouchableOpacityProps & {

// StyleProp는 TextStyle, ImageStyle, ViewStyle 속성을 가지고 있음
  viewStyle?: StyleProp<ViewStyle>
}

export const TouchableView: FC<TouchableViewProps> = ({
  children, viewStyle ,...touchableProps}) => {
  return (
  //...touchableProps는 children, viewStyle 제외 나머지 속성
    <TouchableOpacity {...touchableProps}>
      <View style={[viewStyle]}>{children}</View>
    </TouchableOpacity>
  )
}
728x90