1.安裝
使用堆棧導航器前,請確保已經安裝並配置了react-navigation/native,如果未安裝請參考使用reactnavigation5.x
npm install @react-navigation/stack
or
yarn add @react-navigation/stack
2.使用
import { createStackNavigator } from '@react-navigation/stack'; const Stack = createStackNavigator(); function MyStack() { return ( <Stack.Navigator> <Stack.Screen name="Home" component={Home} /> <Stack.Screen name="Notifications" component={Notifications} /> <Stack.Screen name="Profile" component={Profile} /> <Stack.Screen name="Settings" component={Settings} /> </Stack.Navigator> ); }
完整示例代碼

import * as React from 'react'; import { Button, View } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; function HomeScreen({ navigation }) { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Button title="Go to Profile" onPress={() => navigation.navigate('Profile')} /> </View> ); } function ProfileScreen({ navigation }) { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Button title="Go to Notifications" onPress={() => navigation.navigate('Notifications')} /> <Button title="Go back" onPress={() => navigation.goBack()} /> </View> ); } function NotificationsScreen({ navigation }) { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Button title="Go to Settings" onPress={() => navigation.navigate('Settings')} /> <Button title="Go back" onPress={() => navigation.goBack()} /> </View> ); } function SettingsScreen({ navigation }) { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Button title="Go back" onPress={() => navigation.goBack()} /> </View> ); } const Stack = createStackNavigator(); function MyStack() { return ( <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Notifications" component={NotificationsScreen} /> <Stack.Screen name="Profile" component={ProfileScreen} /> <Stack.Screen name="Settings" component={SettingsScreen} /> </Stack.Navigator> ); } export default function App() { return ( <NavigationContainer> <MyStack /> </NavigationContainer> ); }
3.配置詳解
Stack.Navigator組件參數說明
initialRouteName
默認路由頁面,即默認打開的頁面。如果不配置,默認第一個頁面。
screenOptions
screen參數配置
keyboardHandlingEnabled
導航到新的頁面時虛擬鍵盤是否自動消失,默認true(自動消失)
mode
定義頁面切換渲染過渡的風格
card:使用IOS或Android原生默認的過渡風格
modal:頁面從底部進入屏幕,IOS的默認樣式(Android可能無效)
headerMode
標題渲染模式
float:標題在頂部,切換頁面時動態改變(IOS常用模式)
screen:標題在頂部,切換頁面時隨頁面淡入淡出(Android常用模式)
none:沒有標題
screenOptions參數
title:標題內容
headerShown: 顯示或隱藏標題,與上述headerMode=“null”效果一樣