다양한 네비게이션 중 가장 기본적인 Stack Navigator
(이하 스택 네비게이터)를 다룬다.
전에 다운받았던, /native
라이브러리는 navigator(이하 네비게이터)의 가장 근간이 되는 요소들을 담고 있다.
그리고 각 네비게이터들은 각자의 라이브러리를 가진다.
스택 네비게이터는 /native-stack
라이브러리를 설치해서 구현할 수 있다.
npm install @react-navigation/native-stack
@react-navigation/native-stack
라이브러리는 react-native-screens
에 의존하기 때문에 꼭 올바르게 설치해야 한다.
createNativeStackNavigator
Screen
과 Navigator
를 리턴하는 함수이며, 리턴되는 객체 모두 React component이다.Navigator
는 항상 Screen
엘레멘트를 포함해야 한다.NavigationContainer
navigation state
를 포함한다.// In App.js in a new project
import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
function DetailsScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
이제 두개의 컴포넌트로 구성된 네비게이터가 나온다.
Screen
컴포넌트의 props
name
: 네비게이션에서 이동할 때 쓰이는 이름이다.component
: 해당 Screen
에서 렌더링되는 컴포넌트이다.options
: 해당 Screen
의 옵션을 객체로 지정한다. <Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'Overview' }}
/>
props
로 screenOptions
를 전달한다.