react-native学习笔记四====》配置路由(react-navigation4.x)

1. 核心包安装

yarn add react-navigation

2.安装依赖(前几个官方推荐,最后一个是我app.js里头路由需要的模块)

yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context  react-navigation-stack

依赖装后我的是这样的:

3.React Native 0.60 及更高版本

(1)ios:iOS 上完成自动链接, 请确保你已经安装了Cocoapods 然后运行命令:

cd ios

pod install

cd ..

(2)安卓:在android/app/build.gradle 中 dependencies 选项添加:

implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02

4.在android/app/src/main/java/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); + } + }; + } }

5.index.js或者 app.js中导入 react-native-gesture-handler依赖
import 'react-native-gesture-handler';

6.4.x版本移除了各类导航器,需要手动安装,这里安装一下 StackNavigatorBottomTabNavigator:
yarn add
react-navigation-stack @react-native-community/masked-view react-navigation-tabs

7.app.js中代码:
import React from 'react';
import { Button,View, Text } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

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.navigate('Details')}
        />
      </View>
    );
  }
}

class DetailsScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

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

export default createAppContainer(AppNavigator);

8.跑一下代码:yarn react-native run-react

完美!  

可参考文档:

1.navigation官网:https://reactnavigation.org/docs/zh-Hans/tab-based-navigation.html

2.eact-naviagtion 的API部分:https://reactnavigation.org/docs/zh-Hans/bottom-tab-navigator.html

3.本文参考:https://www.javascriptcn.com/read-99050.html

 

猜你喜欢

转载自www.cnblogs.com/miaSlady/p/12217180.html