NavigationContainer Props

NavigationContainer는 자식 컴포넌트에 navigation, route 두가지 기본 props를 자동으로 넘겨준다.
  • navigation: 화면 전환을 위한 객체
  • route: 현재 화면에 전달된 파라미터와 관련된 정보
2개를 동시에 넘겨주는 경우 어떠헤 하는지 알아보자.

https://github.com/hisimpson1/ReactiveNative_test/blob/main/reactnative_base/tutorial06/App.js

App.js
import * as React from 'react';
import { Button, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>홈 화면</Text>
      <Button
        title="상세 화면으로 이동 (데이터 전달)"
        onPress={() =>
          navigation.navigate('Details', {
            userName: '홍길동',
            age: 25,
          })
        }
      />
    </View>
  );
}

function DetailsScreen({ route, navigation }) {
  // route.params로 전달된 값 받기
  const { userName, age } = route.params || {};

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>상세 화면</Text>
      {userName && <Text>이름: {userName}</Text>}
      {age && <Text>나이: {age}</Text>}
      <Button
        title="홈으로 돌아가기"
        onPress={() => navigation.goBack()}
      />
    </View>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} options={{ title: '홈' }} />
        <Stack.Screen name="Details" component={DetailsScreen} options={{ title: '상세' }} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

다음 문장에서 || 기능을 알아 보자.
const params = route.params || {};
  • route.params가 truthy(값이 존재하는 경우)라면 그대로 사용한다.
  • route.params가 falsy(예: undefined, null, false, 0, 빈 문자열 등)라면, 대신 오른쪽의 빈 객체 {}를 사용한다.
HomeScreen에서 파라메터를 전달해주고 있다.
DetailsScreen에서 라우터와 navigation값을 받는다.
navigation은 별도로 전달하지 않아도 props에서 알아서 자동으로 전달이 된다.
라우터값은 route.params로 전달 받는다.

function HomeScreen({ navigation }) {
        ......
        onPress={() =>
          navigation.navigate('Details', {
            userName: '홍길동',
            age: 25,
          })
       .......
}

function DetailsScreen({ route, navigation }) {
  // route.params로 전달된 값 받기
  const { userName, age } = route.params || {};
  ......
}