๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ฑ Cross Platform/React Native

[React Native] ํ™”๋ฉด ๊ฐ„ ๋ฐ์ดํ„ฐ ์ด๋™ํ•˜๊ธฐ (Passing data between screen)

by Fomagran ๐Ÿ’ป 2022. 6. 18.
728x90
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” Foma ์ž…๋‹ˆ๋‹ค!

 

์˜ค๋Š˜์€ ์ €๋ฒˆ ์‹œ๊ฐ„์— ๋‹ค๋ค˜๋˜ List ํ™”๋ฉด ์— ์ด์–ด์„œ ํŠน์ • ์ปดํฌ๋„ŒํŠธ๋ฅผ ํด๋ฆญ ํ–ˆ์„ ๋•Œ ๋‹ค์Œ ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ•˜๊ณ , ๋ฐ์ดํ„ฐ๋ฅผ ํ•จ๊ป˜ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด์„œ ๋‹ค๋ค„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~

 

์–ธ์–ด๋Š” TypeScript, ํ™˜๊ฒฝ์€ Expo๋กœ ์ง„ํ–‰ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!


Person List

 

Person ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

(๋ฆฌ์ŠคํŠธ ํ™”๋ฉด์€ ์—ฌ๊ธฐ ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”!)

 

Pressable ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ˆŒ๋ €์„ ๋–„ PersonDetatil ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ•˜๊ฒŒ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

(Navigation์— ๋Œ€ํ•œ ๊ฒƒ์€ ์—ฌ๊ธฐ๋ฅผ ์—ฌ๊ธฐ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”)

 

๊ทธ๋ฆฌ๊ณ  ํ•จ๊ผ ๋ณด๋‚ผ ๋ฐ์ดํ„ฐ๋ฅผ { ์ด๋ฆ„1: ๋ณด๋‚ผ ๋ฐ์ดํ„ฐ1, ์ด๋ฆ„2: ๋ณด๋‚ผ ๋ฐ์ดํ„ฐ2...} ์™€ ๊ฐ™์€ ํ˜•์‹์œผ๋กœ ์ž‘์„ฑํ•ด ์ค๋‹ˆ๋‹ค. 

 

PersonListScreen.tsx

 

export default function PersonListScreen({
  navigation,
}: NativeStackHeaderProps) {
  useEffect(() => {
    console.log("Rendering Home Screen");
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={data as Array<Person>}
        renderItem={({ item }: { item: Person }) => {
          return (
            <Pressable
              onPress={() =>
                navigation.navigate("PersonDetail", {
                  name: item.name,
                  age: item.age,
                  gender: item.gender,
                })
              }
            >
              <PersonCell item={item} />
            </Pressable>
          );
        }}
        keyExtractor={(item) => item.name}
      />
    </View>
  );
}

Person Detail

 

๊ฐ€์žฅ ๋จผ์ € ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์•„์˜ฌ(PersonListScreen์—์„œ ๋ณด๋‚ธ ๋ฐ์ดํ„ฐ๋“ค) ๊ฒƒ๋“ค์„ type์œผ๋กœ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

PersonDetailScreen.tsx

 

type DetailParams = {
  route: {
    params: {
      name: string;
      age: string;
      gender: string;
    };
  };
};

 

๊ทธ ๋‹ค์Œ ์œ„์—์„œ ๋ช…์‹œํ•ด ๋†“์€ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ด์šฉํ•ด Text์— ๋‚˜ํƒ€๋‚ด ์ค๋‹ˆ๋‹ค.

 

type Navigation = NativeStackHeaderProps & DetailParams;

export default function PersonDetailScreen({ route }: Navigation) {
  return (
    <View style={styles.container}>
      <Text style={styles.header}>Name: {route.params.name}</Text>
      <Text style={styles.header}>Age: {route.params.age}</Text>
      <Text style={styles.header}>Gender: {route.params.gender}</Text>
    </View>
  );
}

์‹คํ–‰ ํ™”๋ฉด

 

Person List ํ™”๋ฉด์—์„œ ๋ˆ„๋ฅธ ์ปดํฌ๋„ŒํŠธ ๋ฐ์ดํ„ฐ ๊ฐ’์ด Person Detail ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ•˜์—ฌ ๋ณด์—ฌ์ง€๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€