一、配置Tab栏
react-native-tab-navigator
-
运行yarn add react-native-tab-navigator安装包
-
导入 tab 栏组件
import TabNavigator from 'react-native-tab-navigator'
-
导入 tabbar 的组件页面
import Home from './components/tabbar/home' import Search from './components/tabbar/search' import Cart from './components/tabbar/cart' import Me from './components/tabbar/me'
-
使用 TabNavigator 组件创建对应的 Tab 栏结构:
<TabNavigator> <TabNavigator.Item title="首页" selected={this.state.selectedname === 'home'} onPress={() => this.setState({ selectedname: 'home' })} // renderIcon={() => <Icon name="home" size={22} />} // renderSelectedIcon={() => <Icon name="home" size={22} color="#000" />} > <Home></Home> </TabNavigator.Item> <TabNavigator.Item title="搜索" selected={this.state.selectedname === 'search'} onPress={() => this.setState({ selectedname: 'search' })} // renderIcon={() => <Icon name="search" size={22} />} // renderSelectedIcon={() => <Icon name="search" size={22} color="#000" />} > <Search></Search> </TabNavigator.Item> <TabNavigator.Item title="购物车" badgeText={0 + ''} selected={this.state.selectedname === 'cart'} onPress={() => this.setState({ selectedname: 'cart' })} // renderIcon={() => <Icon name="shopping-cart" size={22} />} // renderSelectedIcon={() => <Icon name="shopping-cart" size={22} color="#000" />} > <Cart></Cart> </TabNavigator.Item> <TabNavigator.Item title="会员" selected={this.state.selectedname === 'me'} onPress={() => this.setState({ selectedname: 'me' })} selectedTitleStyle={{ color: 'red' }} // renderIcon={() => <Icon name="user" size={22} />} // renderSelectedIcon={() => <Icon name="user" size={22} color="#000" />} > <Me></Me> </TabNavigator.Item> </TabNavigator>
-
需要在 state 上定义 selectedname来保存当前被选中的tab栏:
constructor() { super() this.state = { selectedname: 'home' } }
二、配置Tab栏的图标
注意:使用图标,需要使用 Android SDK Manager 安装 Android SDK Build-tools 26.0.1 并接收其 license;
react-native-vector-icons
- 运行yarn add react-native-vector-icons安装包
- 运行react-native link,来快速 进行相关的配置;
- 打开android/app/build.gradle,定位到第81行,添加如下代码:
// 自定义项目用用到的 字体文件
project.ext.vectoricons = [
iconFontNames: ['Ionicons.ttf'] // Name of the font files you want to copy
]
// 应用导入的字体文件
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
- 当做完以上3步之后,我们已经手动地修改了安卓的原生代码,因此不要直接刷新代码,这样会报错;我们需要重新运行react-native run-android命令,进行打包编译,并重新部署到手机上,进行调试开发;
- 字体图标已经配置好了,如何用起来呢:
// 导入 字体图标
import Icon from 'react-native-vector-icons/Ionicons'
<TabNavigator.Item
title="首页"
selected={this.state.selectedname === 'home'}
onPress={() => this.setState({ selectedname: 'home' })}
+ renderIcon={() => <Icon name="home" size={22} color="#900" />}
>
<Home></Home>
</TabNavigator.Item>
网友评论