最低要求:react-native版本: react-native >= 0.63.0
React Navigation
由一些核心工具組成,這些工具會被導航器用來創建你應用中的導航結構。
為了預先加載安裝工作,讓我們也安裝和配置大多數導航器使用的依賴項。
安裝
yarn add @react-navigation/native
我們現在要安裝的庫是react-native-screens
和react-native-safe-area-context
。
yarn add react-native-screens react-native-safe-area-context
react-native-screens
包需要一個額外的配置步驟才能在Android設備上正常工作。編輯MainActivity.java
文件,它位于android/app/src/main/java/<你的包名>/MainActivity.java
。
// Add the following code to the body of MainActivity class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
}
// and make sure to add an import statement at the top of this file:
import android.os.Bundle;
使用
現在,我們需要將整個應用程序包裝在NavigationContainer中。通常你會在你的入口文件中這樣做,比如index.js或App.js。
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
<NavigationContainer>{/* Rest of your app code */}</NavigationContainer>
);
}
安裝棧導航器
到目前為止,我們安裝的庫是導航器的構建塊和共享基礎,React Navigation中的每個導航器都有自己的庫。要使用本地堆棧導航器,我們需要安裝@react-navigation/native-stack
:
yarn add @react-navigation/native-stack
createNativeStackNavigator是一個函數,它返回一個包含兩個屬性的對象:Screen和Navigator。它們都是用于配置導航器的React組件。Navigator應該包含Screen元素作為它的子元素來定義路由的配置。
NavigationContainer是一個組件,它管理我們的導航樹并包含導航狀態。該組件必須包裝所有導航器結構。通常,我們會在應用的根目錄下渲染這個組件,它通常是從app .js導出的組
// 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>
);
}
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;