在 App 中 tab 是常见的页面类型,在 RN 里使用 react-navigation 可快速地进行 tab 配置。
假设应用有4个页面,两个是tab页面,两个是详情页面。
App.js
//应用实际场景是有redux的,这里就不删除了。不使用rudex的话,直接 return <Router />就 ok 啦!
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import configureStore from './store';
import Router from './router';
let store = configureStore();
export default class App extends Component {
render() {
return (
<Provider store={store.store} style={{ flex: 1 }}>
<PersistGate persistor={store.persistor}>
<Router />
</PersistGate>
</Provider>
);
}
};
router.js
import { createBottomTabNavigator, createAppContainer, createStackNavigator } from 'react-navigation';
import React from 'react';
import { Image } from 'react-native';
import Index from './view/index';
import Center from './view/center';
import Detail1 from './view/detail1';
import Detail2 from './view/detail2';
const TabNavigator = createBottomTabNavigator({
Index: {
screen: Index,
navigationOptions: {
title: '首页'
}
},
Center: {
screen: Center,
navigationOptions: {
title: '我的'
}
},
}, tabBarConfig);
const AppNavigator = createStackNavigator({
Tab: TabNavigator,
Detail1: Detail1
Detail2: Detail2
}, { headerMode: 'none' });//删除每个页面的头(一般使用自定义的)
export default createAppContainer(AppNavigator);
const tabBarConfig = { //tab的一些配置
defaultNavigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, horizontal, tintColor }) => {//处理tab icon
const { routeName } = navigation.state;
let iconUrl;
switch (routeName) {
case 'Center':
iconUrl = focused ? require('./assets/imgs/me-full.png') : require('./assets/imgs/me.png');
break;
default:
iconUrl = focused ? require('./assets/imgs/mv-full.png') : require('./assets/imgs/mv.png');
break;
}
return <Image source={iconUrl} style={{ width: 25, height: 25 }} />;
},
}),
tabBarOptions: {
activeTintColor: '#fd0',
inactiveTintColor: '#666',
labelStyle: {
fontSize: 14
},
style: {
backgroundColor: '#fafafa',
}
}
}
应用中,跳转非tab页面,建议使用push跳转,跳转tab建议使用navigate进行跳转。
<Text onPress={() => this.props.navigation.navigate('Center')}>跳转Center</Text>
<Text onPress={() => this.props.navigation.push('Detail1')}>跳转Detail</Text>