React Native创建底部导航栏(Bottom Tab)

0.619字数 115阅读 848

搞这个底部导航栏踩了一天的坑,现在把整个过程整理出来记录在下面

创建一个React Native项目,目前React Native最新版本为0.59

react-native init AwesomeProject

安装React Navigation,目前React Navigation最新版本为3.5.1

npm install --save react-navigation

安装react-native-gesture-handler

npm install --save react-native-gesture-handler

链接原生库

react-native link react-native-gesture-handler

在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 Material Bottom Tabs

npm install react-navigation-material-bottom-tabs react-native-paper

安装 Vector Icons

  npm install react-native-vector-icons --save

链接原生库

react-native link react-native-vector-icons

完整代码如下

import React, { Component } from "react";
import { Text, View } from "react-native";
import { createAppContainer } from "react-navigation";
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";
import FontAwesome from "react-native-vector-icons/FontAwesome";

const tabBarIcon = name => ({ tintColor }) => (
  <FontAwesome
    style={{ backgroundColor: "transparent" }}
    name={name}
    color={tintColor}
    size={22}
  />
);
class ExpenseScreen extends React.Component {
  static navigationOptions = {
    tabBarIcon: tabBarIcon("shopping-cart"),
    tabBarLabel:"消费"
  };
  render() {
    return (
      <View>
        <Text>VAEMC</Text>
        <Text>消费</Text>
      </View>
    );
  }
}
class IncomeScreen extends React.Component {
  static navigationOptions = {
    tabBarIcon: tabBarIcon("credit-card"),
    tabBarLabel:"收入"
  };
  render() {
    return (
      <View>
        <Text>VAEMC</Text>
        <Text>收入</Text>
      </View>
    );
  }
}
class MyScreen extends React.Component {
  static navigationOptions = {
    tabBarIcon: tabBarIcon("user"),
    tabBarLabel:"我的"
  };
  render() {
    return (
      <View>
        <Text>VAEMC</Text>
        <Text>我的</Text>
      </View>
    );
  }
}
export default createAppContainer(
  createMaterialBottomTabNavigator({
    Expense: {screen: ExpenseScreen},
    Income: { screen: IncomeScreen },
    My: { screen: MyScreen }
  })
);

效果如下所示

image.png