zl程序教程

您现在的位置是:首页 >  其他

当前栏目

React Native 路由使用总结

2023-04-18 14:44:35 时间

React Native 路由

因 React Native 版本设计到0.44之后,原先的 RN 路由完全失效了,首先我先附上原先路由写法,下面为原先路由代码:
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { StatusBarIOS,Platform } from 'react-native';
import { createMemoryHistory, Router, IndexRoute, Route } from 'react-router';
import { createNavigatorRouter } from 'react-native-navigator-router';


<Provider store={store}>
    <Router history={createMemoryHistory('/')}>
        <Route path='/' component={createNavigatorRouter()}>
            <IndexRoute component={App} />
            <Route path="/about" component={AllRoute} />
        </Route>
    </Router>
</Provider>

因长时间习惯使用 Vue 与 React 的 路由,网上查询各种资料,找出类似 Vue/React的路由使用。但是React Native 升级到0.44 之后,运行直接报错,createMemoryHistory('/') 异常, 也许是我的使用不当,或者说是环境原因,期间我也打开node_model研究过一番,也没整明白,总之呢,无法使用。


路由解决方案1:

PS:

==RN官方声明 从RN 0.43版本开始,官方将停止维护Navigator,建议大家迁移到新的react-navigation库==

RN 官网地址 RN官网 reactnavigation


接下来,我将附上我的 RN 路由代码:

目录介绍

路由配置共分为两个文件:

1、路由(routes.js文件 )。

2、路由配置routesConfig.js文件。

下面为两文件的代码:

1、routes.js 文件代码:

这个文件主要是用于处理 Navigator

import React, {
    Component
} from 'react'
import { View, StyleSheet, Navigator, TouchableHighlight, Text, Dimensions } from 'react-native'
const {
    width,
    height
} = Dimensions.get('window');

import Routes from './routesConfig.js';

export default class UINavigator extends Component {
    _routesLen = Number(Routes.length - 1); //索引从0 开始,路由的长度

    render() {
            const routes = Routes;
            return(
                <Navigator
            initialRoute={routes[0]}//默认第一个索引,可以认为是首页
            initialRouteStack = {routes}//栈
            renderScene={(route,navigator) =>
                <route.component route={route} navigator={navigator} routes={routes}/>
            }
            style = {
                styles.navigator
            }
            configureScene = {
                (route) => {
                    if(route.index) {
                        return Navigator.SceneConfigs.PushFromRight;

                        /*
                            configureScene这个属性是用来配置页面跳转动画和手势的,常用的动画手势如下 
                            - Navigator.SceneConfigs.PushFromRight (default) 
                            - Navigator.SceneConfigs.FloatFromRight 
                            - Navigator.SceneConfigs.FloatFromLeft 
                            - Navigator.SceneConfigs.FloatFromBottom 
                            - Navigator.SceneConfigs.FloatFromBottomAndroid 
                            - Navigator.SceneConfigs.FadeAndroid 
                            - Navigator.SceneConfigs.HorizontalSwipeJump 
                            - Navigator.SceneConfigs.HorizontalSwipeJumpFromRight 
                            - Navigator.SceneConfigs.VerticalUpSwipeJump 
                            - Navigator.SceneConfigs.VerticalDownSwipeJump
                        */
                    }
                }
            }
            navigationBar = {
                    <Navigator.NavigationBar
                routeMapper={{//导航栏路由映射器, 设置左键LeftButton, 右键RightButton, 标题Title.
                    // 左键
                    LeftButton: (route, navigator, index, navState) =>
                    { 
                        if(route.index === 0) {
                            return null;
                        }else {
                            return(
                                <TouchableHighlight onPress={() => {
                                        navigator.jumpBack() //不能是当前栈里面的第一个页面
                                    }}>
                                    <Text style={[styles.titleBar,{left:0}]} >返回</Text>
                                </TouchableHighlight>
                            )
                        }
                    },
                    // 右键
                    RightButton: (route, navigator, index, navState) =>
                    { 
                        if(route.index === this._routesLen) {//
                            return null;
                        }else {
                            return(
                                <TouchableHighlight onPress={() => {
                                    let routes = navigator.getCurrentRoutes()
                                    if (routes.length < 1) {
                                        return;
                                    }
                                    if (routes.pop().index !== route.index) {
                                        navigator.jumpForward() //不能是当前栈里面的最后一个页面
                                    }
                                }}>
                                <Text style={[styles.titleBar,{right:0}]} >下一步</Text>
                                </TouchableHighlight>)
                        }
                    },
                    Title: (route, navigator, index, navState) =>
                    { return (<Text style={styles.TitleCont}>{route.message}</Text>); },
                }}
                style={styles.titleBarBg}
                />
            }
        >
        </Navigator>

        )
    }
}

const styles = StyleSheet.create({
    navigator:{
        width:width,
        height:height,
        backgroundColor:'#999999',
        paddingTop:55,
        flex:1,
    },
    titleBarBg:{
        backgroundColor: '#008dfd',
    },
    TitleCont:{
        fontSize:18,
        color:'#FFFFFF',
        alignItems:"center",
        width:210,
        marginTop:16,
        textAlign: 'center',
        justifyContent:"center",

    },
    titleBar:{
        fontSize:14,
        color:'#ffffff',
        position:"relative",
        top:16,
        width:54,
        height:55,
        paddingLeft:5
    }
})

2、routesConfig.js文件

这个文件主要是用于配置路由组件

import Home from '../views/home'
import App from '../views/stockInfo'
import NetWork404 from '../views/404';
import DemoAnimated from '../views/demo/DemoAnimated.js';

export default Routes = [{
    message: '我的首页',//title
    index: 0,//索引
    component: Home//组件
}, {
    message: '新闻、财务、关于',
    index: 1,
    component: App
}, {
    message: '我的旋转动画',
    index: 2,
    component: DemoAnimated
}, {
    message: '404页面',
    index: 3,
    component: NetWork404
}];

使用

使用就很简单了,例如:

跳转下一页: navigator.push 方法

返回上一页,调用: navigator.pop() 方法, 使用当前页面出栈, 显示上一个栈内页面.例如:

返回第一页,调用: navigator.popToTop()方法


示例代码:

class Page1 extends Component {
    render () {
        return(
            <View style={{backgroundColor:'blue',flex:1}}>
                //跳转到下一页面
                <TouchableHighlight 
                    onPress={() => {
                        this.props.navigator.push(this.props.routes[this.props.route.index+1])
                    }
                    }>
                <Text style={[styles.text,{fontSize:15}]}>第一页</Text>
                </TouchableHighlight>
                <Text style={[styles.text,{fontSize:15}]}>页面显示的内容:这是第一页</Text>
            </View>
        )
    }
}
class ThirdPage extends Component {
    render () {
        return(
            <View style={{backgroundColor:'cornsilk',flex:1}}>

                <TouchableHighlight 
                    onPress={() => {
                        this.props.navigator.pop()//关键代码,返回到上一页
                        }
                    }>
                <Text style={[styles.text,{fontSize:15}]}>第三页pop</Text>
                </TouchableHighlight>


                <TouchableHighlight 
                    onPress={() => {
                        this.props.navigator.popToTop()//返回到第一页,也就是首页
                        }
                    }>
                <Text style={[styles.text,{fontSize:15}]}>返回第一页</Text>
                </TouchableHighlight>
            </View>
        )
    }
}

PS:pop()、 push()jumpBack()、 jumpForward() 的区别:

1、pop()、 push()一组的跳转会改变路由栈 。

2、jumpBack()、 jumpForward()不会改变。


解决方案2:(荐)

官网给的demo 暂时没有封装,特别的简单,特备的方便。

需要安装命令:

npm i react-navigation –save-dev

import React from 'react';
import { AppRegistry,View,Button,Text} from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
    static navigationOptions = {
        title: 'Welcome',
    };
    render() {
        const { navigate } = this.props.navigation;

        return <View>
            <Text>Hello, Navigation!</Text>
            <Button
              onPress={() => navigate('Chat',{ user: 'Lucy' })}
              title="Chat with Lucy"
            />
        </View>;
    }
}

class ChatScreen extends React.Component {
    static navigationOptions = ({ navigation }) => ({
        title: `Chat with ${navigation.state.params.user}`,
    });
    render() {
        const { params } = this.props.navigation.state;
        return (
            <View>
                <Text>Chat with {params.user}</Text>
            </View>
        );
    }
}


const SimpleApp = StackNavigator({
    Home: {
        screen: HomeScreen
    },
    Chat:{
        screen:ChatScreen
    }

});

AppRegistry.registerComponent('Root', () => SimpleApp);

OK,可以了!