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

注意:未经允许不可私自转载,违者必究

猜你喜欢

转载自blog.csdn.net/weixin_40614372/article/details/86237863