1. 程式人生 > >React Native入門篇—react-navigation路由配置

React Native入門篇—react-navigation路由配置

本人學習React Native沒有看過任何教學視訊,都是按照官網一步步學習的。只研究了Android開發,所以下面的教程都是Android開發教程。

注意:未經允許不可私自轉載,違者必究

React Native官方文件:https://reactnative.cn/docs/getting-started/

react-navigation官方網站:https://reactnavigation.org/en/

專案地址GitHub地址:https://github.com/zhouwei1994/nativeCase.git
 

安裝react-navigation

在專案目錄下cmd裡面執行以下命令:

yarn add react-navigation

yarn add react-native-gesture-handler

//連結所有本機依賴項
react-native link react-native-gesture-handler

Android原生配置

下圖前面帶加號的需要加入到 android\app\src\main\java\com\nativecase(nativecase是專案名稱)\MainActivity.java檔案:

package com.reactnavigation.example;

import com.facebook.react.ReactActivity;
+ import com.facebook.react.ReactActivityDelegate;
+ import com.facebook.react.ReactRootView;
+ import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

  @Override
  protected String getMainComponentName() {
    return "Example";
  }

+  @Override
+  protected ReactActivityDelegate createReactActivityDelegate() {
+    return new ReactActivityDelegate(this, getMainComponentName()) {
+      @Override
+      protected ReactRootView createRootView() {
+       return new RNGestureHandlerEnabledRootView(MainActivity.this);
+      }
+    };
+  }
}

react-navigation用法

檢視專案目錄:https://github.com/zhouwei1994/nativeCase/blob/master/README.md

在src/view檔案下建立(專案頁面):

  • 建立home資料夾

建立home.js 檔案

建立button.js 檔案

  • 建立my資料夾

建立my.js 檔案

  • 建立order資料夾

建立order.js 檔案

  • 建立project資料夾

建立project.js 檔案

order.js 檔案如下:

import React, { Component } from 'react';
import { ScrollView, StyleSheet, Text, View, Button, Platform } from 'react-native';
const instructions = Platform.select({
    ios: '蘋果手機才會顯示我',
    android:
        '安卓手機才會顯示我',
});
export default class Order extends Component {
    render() {
        return (
            <ScrollView style={styles.orderPage}>
                <Text style={{fontSize:40}}>路由方法</Text>
                <Text>{instructions}</Text>
                <Button
                    title="跳轉到主選單"
                    onPress={() => this.props.navigation.navigate('my')}
                />
                <View style={{marginBottom:10}}></View>
                <Button
                    title="開啟子頁面"
                    onPress={() => this.props.navigation.push('button', {
                        itemId: 86,
                        otherParam: '你想要的任何東西',
                    })}
                />
                <View style={{marginBottom:10}}></View>
                <Button
                    title="返回上一頁"
                    onPress={() => this.props.navigation.goBack()}
                />
                <View style={{marginBottom:10}}></View>
            </ScrollView>
        );
    }
}
const styles = StyleSheet.create({
    orderPage: {
        backgroundColor: '#f5f5f5',
    },
});

home.js 、my.js、project.js全部都是以下檔案

import React, { Component } from 'react';
import { ScrollView, StyleSheet, Text, View, Button } from 'react-native';
class Home extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <ScrollView>
                <Text style={{fontSize:30}}>react-native頁面</Text>
            </ScrollView>
        );
    }
}
export default Home;
const styles = StyleSheet.create({

});

button.js 檔案如下:

import React, { Component } from 'react';
import { ScrollView, StyleSheet, Text, View, Button } from 'react-native';
class Button extends Component {
    static navigationOptions = {
        title: "子頁面",
        //右邊的按鈕
        headerRight: (
            <Button
                onPress={() => alert('This is a button!')}
                title="按鈕"
                color="#0f0"
                style={{ marginRight: 10 }}
            />
        ),
    };
    constructor(props) {
        super(props)
    }
    render() {
        return (
            <ScrollView>
                <Text style={{fontSize:30}}>子頁面</Text>
            </ScrollView>
        );
    }
}
export default Button;

在src/router檔案下建立:

  1. index.js    頁面路由配置
  2. navigator.js   底部導航配置

navigator.js檔案如下:

import React, { Component } from 'react';
import { StyleSheet, Image } from 'react-native';
import { createBottomTabNavigator, TabBarBottom } from "react-navigation";
//主導航頁面
import Home from './../view/home/home';
import Project from './../view/project/project';
import Order from './../view/order/order';
import My from './../view/my/my';
//主導航設定
export default createBottomTabNavigator(
    {
        home: {
            screen: Home,
            navigationOptions: () => ({
                //底部導航的文字
                tabBarLabel: `首頁`,
                //底部導航的圖示
                tabBarIcon: ({ focused }) => {
                    var imageIcon = require('./../images/tabIcon/ic_home.png');
                    if (focused) {
                        imageIcon = require('./../images/tabIcon/ic_home_active.png');
                    }
                    return <Image style={styles.tabIcon} source={imageIcon} />
                },
            }),
        },
        project: {
            screen: Project,
            navigationOptions: () => ({
                tabBarLabel: `專案`,
                tabBarIcon: ({ focused }) => {
                    var imageIcon = require('./../images/tabIcon/ic_project.png');
                    if (focused) {
                        imageIcon = require('./../images/tabIcon/ic_project_active.png');
                    }
                    return <Image style={styles.tabIcon} source={imageIcon} />
                },
            }),
        },
        order: {
            screen: Order,
            navigationOptions: () => ({
                tabBarLabel: `訂單`,
                tabBarIcon: ({ focused }) => {
                    var imageIcon = require('./../images/tabIcon/ic_order.png');
                    if (focused) {
                        imageIcon = require('./../images/tabIcon/ic_order_active.png');
                    }
                    return <Image style={styles.tabIcon} source={imageIcon} />
                },
            }),
        },
        my: {
            screen: My,
            navigationOptions: () => ({
                tabBarLabel: `我的`,
                tabBarIcon: ({ focused }) => {
                    var imageIcon = require('./../images/tabIcon/ic_my.png');
                    if (focused) {
                        imageIcon = require('./../images/tabIcon/ic_my_active.png');
                    }
                    return <Image style={styles.tabIcon} source={imageIcon} />
                },
            }),
        },
    },
    {
        //首次載入時顯示的頁面
        initialRouteName: "home",
        tabBarComponent: TabBarBottom,
        tabBarPosition: 'bottom',
        tabBarOptions: {
            //當前選中的tab的文字顏色和圖示顏色
            activeTintColor: '#000',
            //當前選中tab的背景顏色
            activeBackgroundColor: "#f5f5f5",
            //當前未選中的tab bar的文字顏色和圖示顏色
            inactiveTintColor: '#666',
            //當前未選中tab的背景顏色
            // inactiveBackgroundColor: "#fff",
            //是否顯示tab的文字
            showLabel: true,
            // 是否顯示tab的圖示
            showIcon: true,
            //tab bar的樣式
            style: {},
            //tab的樣式物件。
            tabStyle: {
                // backgroundColor: '#000',
                // borderTopColor: '#ccc',
            }
        },
        //是否在切換tab頁時使用動畫
        animationEnabled: true,
        //是否允許滑動切換tab頁
        swipeEnabled: true,
        //是否懶載入
        lazy: true,
    }
)
const styles = StyleSheet.create({
    tabIcon: {
        width: 23, height: 24
    }
});

index.js檔案如下:

import React, { Component } from 'react';
import { Easing, Animated,Image } from 'react-native';
import {
    createStackNavigator,
    createAppContainer
} from "react-navigation";
//底部導航配置
import Navigator from './../components/navigator/index';
//頁面
import Button from '../view/home/Button';
//頁面路由
const routerStack = createStackNavigator({
    navigator: {
        screen: Navigator,
        //主導航頁面不顯示頭部
        navigationOptions: {
            header: null,
        }
    },
    button: {
        screen: Button,
    },
}, {
        //預設第一次顯示首頁
        initialRouteName: 'navigator',
        // 定義渲染和過渡的樣式
        mode: 'modal',
        // 指定標頭的呈現方式
        headerMode: "screen",
        //顯示返回圖示後的文字
        headerBackTitleVisible: false,
        cardOverlayEnabled: true,
        //標題居中
        headerLayoutPreset: "center",
        //設定預設資料
        defaultNavigationOptions: ({ navigation }) => {
            return {
                // 設定頭部返回圖片
                headerBackImage: <Image style={{width:22,height:20}} screen={require("../images/nav_back.png")}/>
            }
        },
        //頁面跳轉動畫
        transitionConfig: () => ({
            transitionSpec: {
                duration: 300,
                easing: Easing.out(Easing.poly(4)),
                timing: Animated.timing,
            },
            screenInterpolator: sceneProps => {
                const {layout, position, scene} = sceneProps;
                const {index} = scene;
                const Width = layout.initWidth;
                //沿X軸平移
                const translateX = position.interpolate({
                    inputRange: [index - 1, index, index + 1],
                    outputRange: [Width, 0, -(Width - 10)],
                });
                //透明度
                const opacity = position.interpolate({
                    inputRange: [index - 1, index],
                    outputRange: [0,  1],
                });
                return {opacity, transform: [{translateX}]};
            }
        }),
        //頁面跳轉之前
        onTransitionStart: () => {
            // console.log("頁面跳轉之前");
        },
        //頁面跳轉之後
        onTransitionEnd: () => {
            // console.log("頁面跳轉之後");
        },
    });

export default routerStack;

然後在src/App.js裡面如下:

import React, { Component } from 'react';
import { ToastAndroid, BackHandler, StatusBar } from 'react-native';
import { createAppContainer} from "react-navigation";
import routerStack from "./router/index.js";
export default createAppContainer(routerStack);

專案地址GitHub地址:https://github.com/zhouwei1994/nativeCase.git

注意:未經允許不可私自轉載,違者必究