본문 바로가기

모바일 개발/React Native-이론

Props 객체 인자 이용하여 카톡 프로필, 친구목록 만들기

<개요>

props는 상위 컴포넌트에서 받은 속성값들을 하위 컴포넌트에 전달해주는 객체이다. 

상위 컴포넌트에서 받은 속성 값들은 props에 멤버로 들어간다. 

 

카톡 프로필은 내 프로필이든, 친구들 프로필이든 로직이 같다. 

따라서 카톡 프로필 하나하나 하위 컴포넌트로 만들어 버리면, 중복코드가 많아져서 가독성이 떨어진다. 

이를 위해 프로필 로직은 하나만 만들고, 각 프로필마다 다른 인자 값들을 props로 넘겨 받아 만드는 것이 

훨씬 효율적이다. 

 

여기서 해볼 것은 하나의 프로필 로직을 만들고, 프로필 별로 다른 값들을 props로 받아서 구현할 것이다. 

 

하위 컴포넌트를 선언한 부분과 호출한 부분이 따로 나뉘는 걸 볼 수 있다. 

호출한 부분에서 받은 속성 값들을 props가 멤버로 받아서 선언 부분에 전달해준다. 

1. 코드 리뷰

import React from 'react';
import { Image, ScrollView, StyleSheet, View, Text } from 'react-native';

/**
 * Header
 * MyProfile
 * Division
 * FriendSection
 * FriendList
 */

const Header = (props) => {
    return <Text>{props.title}</Text>
}
//변동사항인 이름, 카톡프로필, 프로필 사이즈는 속성으로 써서 props로 보냄.
const MyProfile = () => {
  return <Profile 
          name="수민" 
          uri="https://www.sisain.co.kr/news/photo/202110/45791_82634_4851.jpg"
          profileSize={40}
          />;
}

const Division = () => {
  return <Text> Division</Text>
}

const FriendSection = () => {
  return <Text> FriendSection</Text>
}

const FriendList = () => {
  return (
    <View>
      <Profile  
        name="명현" 
        uri="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT0Yr6EHXBuyFT758YQZJIfRS-OxlHLe_xLpmjfq51POfIrnezVU4RRjEPUrbxCI-62hqo&usqp=CAU"
        profileSize={30}
      />
      <Profile  
        name="민혁" 
        uri="https://cdn.healthinnews.co.kr/news/photo/202204/29034_29822_2928.jpg"
        profileSize={30}
      />
      <Profile  
        name="상로" 
        uri="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQhPp9xC6b6117NcTAyvXr5rw0jwhBp-l3_CrjegZByjEzObtv0AXEbgy8LvorDqf3CKmI&usqp=CAU"
        profileSize={30}
      />
      <Profile  
        name="재욱" 
        uri="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ9-fJsY_Vm3jmGZh0ZRdIW6c8xcGfNkfhHkpKpKLl1W0ac7luUWx-DTawzIP_dU8ljcWA&usqp=CAU"
        profileSize={30}
      />
      <Profile  
        name="규범" 
        uri="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxZTogMJ6-sBn0-3YBTCsUGSWFjDX_LOpiw_wQ8hEQamKuG4QZeZqQXSWARGetJ9B0CL4&usqp=CAU"
        profileSize={30}
      />
    </View>
  )
}

/*함수형 컴포넌트로 표현 */
 const Profile = (props) => {
   return(
     <View style={{flexDirection: "row"}}>
       <Image source={{
           uri: props.uri
          }}
           style={{
             width: props.profileSize,
             height: props.profileSize,
          }}          
           />
       <Text>{props.name}</Text>
     </View>
   )
 }






const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

2. 스스로 해보기 

import { setStatusBarBackgroundColor } from "expo-status-bar";
import react from "react";
import { Image, View, Text, StyleSheet } from "react-native";

const Header = (props) => {
  return<Text>{props.title}</Text>
}

const MyProfile = () => {
  return(
    <Profile
      name = "수민"
      uri = "https://i.ytimg.com/vi/qDhOhTtPLng/maxresdefault.jpg"
      fontSize = {40}
    />
  )
}

const Division = () => {
  return(
    <Text>Division</Text>
  )
}

const FriendSection = () => {
  return(
    <Text>FriendSection</Text>
  )
}

const FriendList = () => {
  return(
    <View>
    <Profile
      name = "지훈"
      uri = "https://www.sisain.co.kr/news/photo/202110/45791_82634_4851.jpg"
      fontSize = {40}
    />
        <Profile
      name = "민혁"
      uri = "https://cdn.healthinnews.co.kr/news/photo/202204/29034_29822_2928.jpg"
      fontSize = {40}
    />
        <Profile
      name = "상로"
      uri = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqKqzXig2zL4ZUAvFgNqn1VG4vxsj3rUoIwvSCy_mATvLxYrbUHiXLSVCwAq_MRoSxAKg&usqp=CAU"
      fontSize = {40}
    />
        <Profile
      name = "재욱"
      uri = "http://www.newsjinju.kr/news/photo/202101/16352_20174_1135.jpeg"
      fontSize = {40}
    />
        <Profile
      name = "규범"
      uri = "https://blog.kakaocdn.net/dn/c7dQje/btrAb9oL0Ke/WAad01aEfiHJdnyVaZBe4K/img.png"
      fontSize = {40}
    />

    </View>
  )
}

const Profile = (props) => {
  return(
    <View style={{flexDirection: "row"}}>
      <Image source={{
        uri: props.uri
      }}
        style = {{
          width: props.fontSize,
          height: props.fontSize
        }}
        />
    <Text>{props.name}</Text>
    </View>
  )
}

export default function App() {
  return (
    <View style={styles.container}>
      <Header title="친구목록"/>
      <MyProfile/>
      <Division/>
      <FriendSection/>
      <FriendList/>
    </View>
  )
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

CSS 가 적용이 안되었는데, View의 속성으로 Style이 아닌 Styles라고 쳐서 그랬다. 30분 정도 소비 했다.