React-native 之路由跳转React Navigation

React Navigation的使用介绍

新手上路,为什么要使用它?目的: 在项目中添加多页面,实现页面之间的跳转;
踩坑:在模拟器中频繁报错,报错内容就不说了,反正看两百遍也看不明白。
主要问题:没有详细查看文档,也是因为起初并不了解如何才能实现路由之间的跳转,也并未直接查找这个包。
官方文档:https://reactnavigation.org/docs/en/getting-started.html

PS: 目前只在windows 上搭建了项目环境,在模拟器和真机上进行了基础的调试,flex布局等;一天一步吧。。

//一、使用步骤
//1、安装依赖,使用yarn 或 npm
yarn add react-navigation
# or with npm
# npm install --save react-navigation

//2、这就是被我忽略的部分
yarn add react-native-gesture-handler
# or with npm
# npm install --save react-native-gesture-handler

// 链接所有本机依赖项
react-native link react-native-gesture-handler

按部就班,完成以上操作即可。注:android模拟器正常,ios没条件,可以自行尝试。

//二、复制如下代码到App.js
import React from 'react';
import { View, Text, Button } from 'react-native';
import { createAppContainer, createStackNavigator, StackActions, NavigationActions } from 'react-navigation'; // Version can be specified in package.json

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            this.props.navigation.dispatch(StackActions.reset({
              index: 0,
              actions: [
                NavigationActions.navigate({ routeName: 'Details' })
              ],
            }))
          }}
        />
      </View>
    );
  }  
}

class DetailsScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
      </View>
    );
  }  
}

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomeScreen,
  },
  Details: {
    screen: DetailsScreen,
  },
}, {
    initialRouteName: 'Home',
});

export default createAppContainer(AppNavigator);

相关api可参考 https://blog.csdn.net/u011272795/article/details/80915040

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容