接續上篇
點選登入後,會跳出「登入成功」提示
此時要將使用者導向首頁
那麼在React Native要如何做到「畫面導向」功能
本篇會使用react-navigation/native套件完成「畫面導向」
官方網站:https://reactnavigation.org/docs/getting-started/
版本:6.1.7
在Web裡,往往會使用location.href..等其他JavaScript指令完成頁面跳轉
而APP則是使用導航器(Navigator)跳轉畫面
平常在使用Facebook APP時,切換通知、個人檔案、功能表
切換功能時,就已經觸發導航器了
安裝指令npx expo install @react-navigation/native @react-navigation/native-stack
官網指示Expo專案需安裝其餘兩項依賴項目npx expo install react-native-screens react-native-safe-area-context
延續上篇登入頁結構,建立空白首頁、導航器Js
路徑結構如以下所示
PracticeExpoApp
├── App.js
├── Navigation
│   └── AppNavigator.js //導航器
├── app.json
├── babel.config.js
├── img
│   └── logo.png
├── package-lock.json
├── package.json
├── src
│   └── Home
│       ├── IndexScreen.js //首頁畫面
│       └── LoginScreen.js //登入畫面
└── tailwind.config.js
在AppNavigator.js引入這兩項
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
NavigationContainer為最外層導航容器,管理、監聽所有子導航器的內容
createStackNavigator堆疊導航器,可以將所有元件組裝成一座導航橋樑,互相溝通
將登入畫面、首頁畫面放到導航容器裡
import LoginScreen from "../src/Home/LoginScreen";
import IndexScreen from "../src/Home/IndexScreen";
export default function AppNavigator() {
  const RootStack = createStackNavigator();
  return (
    <NavigationContainer>
      <RootStack.Navigator
        screenOptions={{
          headerShown: false,
        }}
        initialRouteName="Login"
      >
        <RootStack.Screen
          name="Index"
          component={IndexScreen}
          options={{ title: "首頁" }}
        />
        <RootStack.Screen
          name="Login"
          component={LoginScreen}
          options={{ title: "登入" }}
        />
      </RootStack.Navigator>
    </NavigationContainer>
  );
}
程式碼講解:
RootStack名稱可以自行定義initialRouteName可以選擇預設畫面(對應到自行定義的name)component就做幾個Screen,component裡還能在做StackStack、群組管理StackScreen都擠在RootStackimport AppNavigator from "./Navigation/AppNavigator";
export default function App() {
  return (
    <SafeAreaView className="flex-1">
      <StatusBar style="auto" />
      <AppNavigator />
    </SafeAreaView>
  );
}
export部分,加上navigation參數export default function LoginScreen({ navigation })navigation參數,就能使用導航相關功能function onLogin() {
    if (loginInfo.Account === "" || loginInfo.Password === "") {
      Alert.alert("失敗","請輸入使用者資訊");
      return false;
    } else{
      Alert.alert("訊息", "登入成功!");
      navigation.navigate("Index");
    }
}
※navigation.navigate帶的參數是name而不是component
可參考上方AppNavigator.js程式碼
import { View, Text } from "react-native";
export default function IndexScreen({ navigation }) {
  return (
    <View className="flex-1 items-center justify-center">
      <Text>我是登入後首頁</Text>
    </View>
  );
}
來看一下結果
成功看到導航後畫面🆗
結語:
到這邊,你的APP已經能正常登入
讓使用者進入登入後首頁畫面
不過目前會有一個問題是
只要重新打開APP,又會返回登入畫面
甚至沒有「登出」功能
舉個例子,Facebook和Instagram就算重新開APP
也不會重新要求使用者輸入帳號密碼
當然有些APP會有例外(Ex:網銀、金流相關APP)
牽扯到「錢」一定要加強資安保護,閒置過久就要重新登入的機制
在開發「永久性登入登出機制」前
下一篇,將回頭講解React Native 基礎進階知識
也就是Effect Hooks、Context Hooks及儲存容器(AsyncStorage)。