react navigation의 stack navigator는 navigation history
를 관리하고 스크린 간의 이동을 할 수 있게 해준다.
가장 많이 쓰이는 navigator로는 createStackNavigator
가 있다.
yarn add @react-navigation/stack
CreateStackNavigator
는 2개의 프로퍼티 Screen
과 Navigator
를 포함하는 객체를 리턴하는 함수다.
Navigator
는 자식 element로 screen
을 포함해야한다.
NavigationContainer
는 navigation tree를 관리하고 navigation 상태를 포함하는 컴포넌트다. 보통은 App의 root에서 이 컴포넌트를 렌더한다.
import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
모든 route 구성은 navigator의 props로 명시된다.
stack navigator에 2번째 screen을 추가해보고 첫번째로 render하기 위한 Home Screen을 구성해보자
function DetailsScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
이제 stack은 2개의 route(Home,Details)를 가진다.
navigator의 각 스크린들은 몇개의 옵션들을 명시할 수 있다. 예를들면 header에 render하기 위한 타이틀을 설정할 수 있다. 이러한 옵션들은 screen component를 위한 options prop
으로 전달할 수 있다.
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'Overview' }}
/>
때때로, navigator의 모든 스크린에 같은 옵션을 주고 싶을 때가 있다. 이 경우에는 navigator에 screenOptions
prop을 전달하면 된다.