웹, 앱 개발/RN React-Native

[React Native] Text - Functional Component Hooks

나아가는중 2021. 1. 23. 22:45
반응형

React Native에서  Hooks를 사용하여 Text component를 만들기

React Native 개발을 class component 형식에서 functional component 형식으로 점점 추세가 바뀌고 있습니다.

검색을 해도 class component로 만든 예제가 거의 대부분이라서 제가 직접 글을 써봅니다...

 

component화를 시키면 재사용성이나 유지보수 등의 장점이 있습니다.

기본적인 Text도 앱에서 공통으로 사용될 Text component를 만들어 사용하면 나중에 쉽게 유지보수 등이 가능해 질텐데요, 이번에 그래서 Text를 hooks를 사용한 fuctional component로 만들어 보았습니다.

 

AppText.js

import React from 'react';
import { StyleSheet, Text } from 'react-native';
import { fonts } from '../../config/globalStyles';

const AppText = ({
    style,
    weight,
    children,
    ...props
}) => {
    let fontFamily = 'medium'
    if (weight === 'light')
        fontFamily = fonts.NotoSansKR_Light;
    else if (weight === 'bold')
        fontFamily = fonts.NotoSansKR_Bold;

    return (
        <Text
            style={{
                ...styles.default,
                style,
            }}
            {...props}
        >
            {children}
        </Text>
    )
}

const styles = StyleSheet.create({
    default: {
        fontSize: 10,
    }
})

export default AppText;

globalStyles에 따로 저장해둔 fonts들 때문에 그대로 복사하셔서 사용하시면 안되실거예요...

예시로만 보여드리는 거니깐 원하시는 조건에 맞춰 사용하시면 됩니다~

저도 아직 초보여서 잘 짠 코드는 아니지만 참조하세요~!

반응형