ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React Native 컴포넌트 Function Component / Class Component 차이
    개발 공부/혼자 하는 리액트 네이티브 2023. 2. 3. 00:07

    컴포넌트란 쉽게 말하면 OOP 에서 하나의 object 같은 존재다.

    중복되는 디자인과 속성을 component 로 만들면 페이지에서 import 하여 굳이 여러번 반복하여 디자인과 속성을 쓰지 않아도 component 를 이용하려 쉽게 페이지를 만드는 것 가능하다. 중복되지 않는 디테일은 props 나 state 를 parameter 처럼 전달해 바꿔가며 사용이 가능하다.

     

    예를 들기 위해 아래 CircleImageWithLabel 라는 component 를 만들었다. 이미지를 동그랗게 display 하고 그 아래 text 를 배치하는 것인데 이미지와 text 의 내용을 props 로 전달 받아 페이지마다 적절하게 사용이 가능하다.

     

    사용법은 아래와 같다. CircleImageWithLabel이 내가 만든 커스텀 Component이며, imageUri와 label이 parameter 역할을 하는 props이다. Import 해주고 첫번째는 '라벨1', 두번째는 '라벨2'로 다르게 props를 주었다.

    import CircleImageWithLabel from '../components/CircleImageWithLabel';
    
    <CircleImageWithLabel imageUri='링크' label='라벨1'/>
    <CircleImageWithLabel imageUri='링크' label='라벨2'/>

    결과물 : 

     

    Function Component 와 Class Component

    Component 는 크게 function component 와 class component 로 나뉜다. 역할은 똑같고 만들기를 function 타입으로 만들지 class 타입으로 만들지의 차이이다. syntax 차이는 아래 예시에서 볼 수 있다. 

    Function Component 예시

    import React from 'react';
    import {View, Image, StyleSheet, Text,} from 'react-native';
    
    type CircleImageWithLabelProps = {
      label: string,
      imageUri: string,
    }
    
    const CircleImageWithLabel = ({ imageUri, label}: CircleImageWithLabelProps) => {
      return (
        <View style={styles.container}>
          <Image
            style={{
              resizeMode: 'contain',
              height: 100,
              width: 100,
              borderRadius: 50,
            }}
            source={{uri: imageUri}}
          />
          <Text>{label}</Text>
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        textAlign: 'center',
        margin: 5,
        width: 110,
        height: 110,
      },
    });
    
    export default CircleImageWithLabel;

     

    Class Component 예시

    import React, {Component} from 'react';
    import {View, Image, StyleSheet, Text} from 'react-native';
    
    type Props = {
      label: string,
      imageUri: string,
    };
    
    class CircleImageWithLabel2 extends Component<Props> {
      constructor(props : Props){
        super(props);
      }
    
      render() {
        return (
          <View style={styles.container}>
            <Image
              style={{
                resizeMode: 'contain',
                height: 100,
                width: 100,
                borderRadius: 50,
              }}
              source={{uri: this.props.imageUri}}
            />
            <Text>{this.props.label}</Text>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        textAlign: 'center',
        margin: 5,
        width: 110,
        height: 110,
      },
    });
    
    export default CircleImageWithLabel2;

     

    차이점 / 장단점

    궁금해서 차이점을 찾아보았는데 React 16.8 이상 부터는 큰 차이가 없는 것 같다. 

    Functional Component 에서는 setState 과 Life-cycle Hooks이 지원되지 않았었는데 React 16.8부터 두개 다 지원되게 업데이트 되었다. 

    Functional Component 가 쓰기 쉬우며 application performance 를 높이는데 좋다고 나와는 있는데 큰 영향은 없어 보인다.

    그냥 큰 차이는 없는 걸로 😋

    반응형
Designed by Tistory.