react-navigation 使用详解

来源:互联网 发布:七天精通js 编辑:程序博客网 时间:2024/05/20 08:23

一、开源库介绍


今年1月份,新开源的React-natvigation库备受瞩目。在短短不到3个月的时间,github上星数已达4000+。Fb推荐使用库,并且在react Native当前最新版本0.44中将Navigator删除。react-navigation据称有原生般的性能体验效果。可能会成为未来React Native导航组件的主流军。本篇内容基于【 ^1.0.0-beta.9 】版本来介绍关于该库的使用和实战技巧。可以看到,虽然是beta版本,不过基本稳定,大家可放心在项目中使用。该库包含三类组件:

(1)StackNavigator:用来跳转页面和传递参数

(2)TabNavigator:类似底部导航栏,用来在同一屏幕下切换不同界面

(3)DrawerNavigator:侧滑菜单导航栏,用于轻松设置带抽屉导航的屏幕


二、react-navigation使用


具体内容大致分为如下:

(1)react-navigation库属性介绍

(2)StackNavigator、TabNavigator实现界面间跳转,Tab切换

(3)StackNavigator界面间跳转、传值、取值

(4)DrawerNavigator实现抽屉导航菜单

(5)DrawerNavigator扩展功能

(6)自定义react-navigation


1、StackNavigator属性介绍

[html] view plain copy
  1. navigationOptions:配置StackNavigator的一些属性。  
  2.   
  3.     title:标题,如果设置了这个导航栏和标签栏的title就会变成一样的,不推荐使用  
  4.     header:可以设置一些导航的属性,如果隐藏顶部导航栏只要将这个属性设置为null  
  5.     headerTitle:设置导航栏标题,推荐  
  6.     headerBackTitle:设置跳转页面左侧返回箭头后面的文字,默认是上一个页面的标题。可以自定义,也可以设置为null  
  7.     headerTruncatedBackTitle:设置当上个页面标题不符合返回箭头后的文字时,默认改成"返回"  
  8.     headerRight:设置导航条右侧。可以是按钮或者其他视图控件  
  9.     headerLeft:设置导航条左侧。可以是按钮或者其他视图控件  
  10.     headerStyle:设置导航条的样式。背景色,宽高等  
  11.     headerTitleStyle:设置导航栏文字样式  
  12.     headerBackTitleStyle:设置导航栏‘返回’文字样式  
  13.     headerTintColor:设置导航栏颜色  
  14.     headerPressColorAndroid:安卓独有的设置颜色纹理,需要安卓版本大于5.0  
  15.     gesturesEnabled:是否支持滑动返回手势,iOS默认支持,安卓默认关闭  
  16.    
  17.   
  18. screen:对应界面名称,需要填入import之后的页面  
  19.   
  20. mode:定义跳转风格  
  21.   
  22.    card:使用iOS和安卓默认的风格  
  23.   
  24.    modal:iOS独有的使屏幕从底部画出。类似iOS的present效果  
  25.   
  26. headerMode:返回上级页面时动画效果  
  27.   
  28.    float:iOS默认的效果  
  29.   
  30.    screen:滑动过程中,整个页面都会返回  
  31.   
  32.    none:无动画  
  33.   
  34. cardStyle:自定义设置跳转效果  
  35.   
  36.    transitionConfig: 自定义设置滑动返回的配置  
  37.   
  38.    onTransitionStart:当转换动画即将开始时被调用的功能  
  39.   
  40.    onTransitionEnd:当转换动画完成,将被调用的功能  
  41.   
  42. path:路由中设置的路径的覆盖映射配置  
  43.   
  44. initialRouteName:设置默认的页面组件,必须是上面已注册的页面组件  
  45.   
  46. initialRouteParams:初始路由参数  


:大家可能对于path不太理解。path属性适用于其他app或浏览器使用url打开本app并进入指定页面。path属性用于声明一个界面路径,例如:【/pages/Home】。此时我们可以在手机浏览器中输入:app名称://pages/Home来启动该App,并进入Home界面。


2、TabNavigator属性介绍

[html] view plain copy
  1. screen:和导航的功能是一样的,对应界面名称,可以在其他页面通过这个screen传值和跳转。  
  2.   
  3.   
  4. navigationOptions:配置TabNavigator的一些属性  
  5.   
  6. title:标题,会同时设置导航条和标签栏的title  
  7.   
  8. tabBarVisible:是否隐藏标签栏。默认不隐藏(true)  
  9.   
  10. tabBarIcon:设置标签栏的图标。需要给每个都设置  
  11.   
  12. tabBarLabel:设置标签栏的title。推荐  
  13.   
  14. 导航栏配置  
  15.   
  16. tabBarPosition:设置tabbar的位置,iOS默认在底部,安卓默认在顶部。(属性值:'top','bottom')  
  17.   
  18. swipeEnabled:是否允许在标签之间进行滑动  
  19.   
  20. animationEnabled:是否在更改标签时显示动画  
  21.   
  22. lazy:是否根据需要懒惰呈现标签,而不是提前,意思是在app打开的时候将底部标签栏全部加载,默认false,推荐为true  
  23.   
  24. trueinitialRouteName: 设置默认的页面组件  
  25.   
  26. backBehavior:按 back 键是否跳转到第一个Tab(首页), none 为不跳转  
  27.   
  28. tabBarOptions:配置标签栏的一些属性iOS属性  
  29.   
  30. activeTintColor:label和icon的前景色 活跃状态下  
  31.   
  32. activeBackgroundColor:label和icon的背景色 活跃状态下  
  33.   
  34. inactiveTintColor:label和icon的前景色 不活跃状态下  
  35.   
  36. inactiveBackgroundColor:label和icon的背景色 不活跃状态下  
  37.   
  38. showLabel:是否显示label,默认开启 style:tabbar的样式  
  39.   
  40. labelStyle:label的样式安卓属性  
  41.   
  42. activeTintColor:label和icon的前景色 活跃状态下  
  43.   
  44. inactiveTintColor:label和icon的前景色 不活跃状态下  
  45.   
  46. showIcon:是否显示图标,默认关闭  
  47.   
  48. showLabel:是否显示label,默认开启 style:tabbar的样式  
  49.   
  50. labelStyle:label的样式 upperCaseLabel:是否使标签大写,默认为true  
  51.   
  52. pressColor:material涟漪效果的颜色(安卓版本需要大于5.0)  
  53.   
  54. pressOpacity:按压标签的透明度变化(安卓版本需要小于5.0)  
  55.   
  56. scrollEnabled:是否启用可滚动选项卡 tabStyle:tab的样式  
  57.   
  58. indicatorStyle:标签指示器的样式对象(选项卡底部的行)。安卓底部会多出一条线,可以将height设置为0来暂时解决这个问题  
  59.   
  60. labelStyle:label的样式  
  61.   
  62. iconStyle:图标样式  

3、DrawerNavigator属性介绍
  

[html] view plain copy
  1. DrawerNavigatorConfig  
  2.   
  3.     drawerWidth - 抽屉的宽度  
  4.     drawerPosition - 选项是左或右。 默认为左侧位置  
  5.     contentComponent - 用于呈现抽屉内容的组件,例如导航项。 接收抽屉的导航。 默认为DrawerItems  
  6.     contentOptions - 配置抽屉内容  
  7.   
  8.     initialRouteName - 初始路由的routeName  
  9.     order - 定义抽屉项目顺序的routeNames数组。  
  10.     路径 - 提供routeName到路径配置的映射,它覆盖routeConfigs中设置的路径。  
  11.     backBehavior - 后退按钮是否会切换到初始路由? 如果是,设置为initialRoute,否则为none。 默认为initialRoute行为  
  12.   
  13.    DrawerItems的contentOptions属性  
  14.   
  15.     activeTintColor - 活动标签的标签和图标颜色  
  16.     activeBackgroundColor - 活动标签的背景颜色  
  17.     inactiveTintColor - 非活动标签的标签和图标颜色  
  18.     inactiveBackgroundColor - 非活动标签的背景颜色  
  19.     内容部分的样式样式对象  
  20.     labelStyle - 当您的标签是字符串时,要覆盖内容部分中的文本样式的样式对象  
从上述中大致了解了react-navigation三种组件的一些基本属性,所以到我们甩起袖子撸代码见证下奇迹了。

4、使用StackNavigator + TabNavigator实现Tab界面切换、界面间导航


API定义:StackNavigator(RouteConfigs, StackNavigatorConfig)、TabNavigator(RouteConfigs, TabNavigatorConfig)

(1)集成 react-navigation:在终端执行 【 npm install react-navigation --save 】

(2)界面中导入必要组件:

[html] view plain copy
  1. import {StackNavigator,TabNavigator,TabBarBottom} from 'react-navigation';  
  2. import HomeScreen from './pages/HomePage';  
  3. import MineScreen from './pages/MinePage';  
(3)定义TabNavigator:
[html] view plain copy
  1. const Tab = TabNavigator(  
  2.   {  
  3.     Home:{  
  4.       screen:HomeScreen,  
  5.       navigationOptions:({navigation}) => ({  
  6.         tabBarLabel:'首页',  
  7.         tabBarIcon:({focused,tintColor}) => (  
  8.           <TabBarItem  
  9.             tintColor={tintColor}  
  10.             focused={focused}  
  11.             normalImage={require('./imgs/nav_fav@2x.png')}  
  12.             selectedImage={require('./imgs/nav_fav_actived@3x.png')}  
  13.           />  
  14.         )  
  15.       }),  
  16.     },  
  17.   
  18.     Mine:{  
  19.           screen:MineScreen,  
  20.           navigationOptions:({navigation}) => ({  
  21.           tabBarLabel:'我',  
  22.           tabBarIcon:({focused,tintColor}) => (  
  23.             <TabBarItem  
  24.              tintColor={tintColor}  
  25.               focused={focused}  
  26.               normalImage={require('./imgs/tab_me_nor@3x.png')}  
  27.               selectedImage={require('./imgs/tab_me_selected@2x.png')}  
  28.             />  
  29.           )  
  30.         }),  
  31.       },  
  32.     },  
  33.   
  34.     {  
  35.       tabBarComponent:TabBarBottom,  
  36.       tabBarPosition:'bottom',  
  37.       swipeEnabled:false,  
  38.       animationEnabled:false,  
  39.       lazy:true,  
  40.       tabBarOptions:{  
  41.         activeTintColor:'#06c1ae',  
  42.         inactiveTintColor:'#979797',  
  43.         style:{backgroundColor:'#ffffff',},  
  44.         labelStyle: {  
  45.               fontSize: 20, // 文字大小  
  46.           },  
  47.       }  
  48.         
  49.     }  
  50.   
  51.   );  
TabBarItem为封装的组件:
[html] view plain copy
  1. import React,{Component} from 'react';  
  2. import {Image} from 'react-native';  
  3.   
  4. export default class TabBarItem extends Component {  
  5.   
  6.     render() {  
  7.         return(  
  8.             <Image source={ this.props.focused ? this.props.selectedImage : this.props.normalImage }  
  9.                 style={ { tintColor:this.props.tintColor,width:25,height:25 } }  
  10.             />  
  11.         )  
  12.     }  
  13.       
  14. }  
可以看到,我们定义了一个名称为【Tab】的TabNavigator的导航组件。在组件中,分为两层参数:

(1)第一层参数定义了要切换的界面,即【首页】、【我】两个界面组件,通过screen属性指定。并且通过navigationOptions属性设置相关属性参数。

(2)设置导航栏的属性参数。

TabNavigator定义好之后,需要用StackNavigator,顾名思义,StackNavigator就是以栈的方式来存放整个界面的,而TabNavigator是作为一个界面内不同子界面之间切换。所以还需要我们定义StackNavigator:
[html] view plain copy
  1. const Navigator = StackNavigator(  
  2.     
  3.   {  
  4.     Tab:{screen:Tab},  
  5.     Product:{screen:ProductScreen}  
  6.   },  
  7.   
  8.   {  
  9.     navigationOptions:{  
  10.       headerBackTitle:null,  
  11.       headerTintColor:'#333333',  
  12.       showIcon:true,  
  13.      swipeEnabled:false,  
  14.      animationEnabled:false,  
  15.     },  
  16.   
  17.     mode:'card',  
  18.   });  
看起来和TabNavigator很相似,同样是指定了两个参数:

(1)指定要跳转的界面组件。同样是screen属性标识界面组件,不多赘述。

(2)定义跳转属性参数,即顶部导航栏的一些参数设置和跳转方式。

可以看到,我们将Tab作为一个界面设置到了StackNavigator。这样就可以实现Tab导航和界面间跳转的效果了。

最后就是在render中引用StackNavigator:
[html] view plain copy
  1. export default class Demo extends Component {  
  2.   
  3.   render() {  
  4.         return (  
  5.           <Navigator />  
  6.         );  
  7.   }  
  8. }  
StackNavigator还提供了onNavigationStateChange回调方法,用来监听导航状态的改变。具体不再赘述。实现了界面跳转和切换,那么就该来增加下界面之间的感情了,来看看如何实现界面之间的传值和取值。


5、界面间跳转、传值、取值


在界面组件注入到StackNavigator中时,界面组件就被赋予了navigation属性,即在界面组件中可以通过【this.props.navigation】获取并进行一些操作。

navigation属性中提供了很多的函数简化界面间操作,简单列举几点:

(1)通过navigate函数实现界面之间跳转:

[html] view plain copy
  1. this.props.navigation.navigate('Mine');  
参数为我们在StackNavigator注册界面组件时的名称。同样也可以从当前页面返回到上一页:
[html] view plain copy
  1. // 返回上一页  
  2. this.props.navigation.goBack();  
(2)跳转时传值:
[html] view plain copy
  1. this.props.navigation.navigate('Mine',{info:'传值过去'});  
第一个参数同样为要跳转的界面组件名称,第二个参数为要传递的参数,info可以理解为key,后面即传递的参数。

(3)获取值:

[html] view plain copy
  1. {this.props.navigation.state.params.info}  
通过state.params来获取传来的参数,后面为key值。此处为info。

以上实现完成,我们就可以愉快的玩耍啦~~ 什么?忽然发现在Android上的效果和IOS效果不一样。老板要界面一致哇~ 怎么办?那就需要我们进行简单的适配了。


三、DrawerNavigator实现抽屉导航


1、导航实现

API定义:DrawerNavigator(RouteConfigs,DrawerNavigatorConfig)

(1)界面中定义DrawerNavigator:
[html] view plain copy
  1. import React,{Component} from 'react';import {AppRegistry, Text, View, StyleSheet, Image, Button, ScrollView,}  from 'react-native';import {DrawerNavigator , DrawerItems} from 'react-navigation';class MyHomeScreen extends React.Component {    static navigationOptions = {        //{ focused: boolean, tintColor: string }        drawerLabel: 'Home',        //{ focused: boolean, tintColor: string }        drawerIcon: ({ tintColor }) => (            <Image                source={require('../../img/ic_image.png')}                style={[styles.icon, {tintColor: tintColor}]}            />        ),    };    render() {        return (            <View style={{paddingVertical: 20, paddingHorizontal: 15}}>                <Text>Hmoe</Text>                <Button                    onPress={() => this.props.navigation.navigate('DrawerOpen')}                    title="open drawer"                />            </View>        );    }}const MyNotificationsScreen = ({navigation}) => (    <View style={{paddingVertical: 20, paddingHorizontal: 15}}>        <Text>NotificationsScreen</Text>        <Button            onPress={() => navigation.navigate('DrawerOpen')}            title="open drawer"        />    </View>);MyNotificationsScreen.navigationOptions = {    drawerLabel: 'Notifications',    drawerIcon: () => (        <View>            <Image                source={require('../../img/ic_me.png')}                style={styles.icon}            />        </View>    ),};const MyFirstProject = DrawerNavigator({    Home: {        screen: MyHomeScreen,    },    Notifications: {        screen: MyNotificationsScreen,    },},{    drawerWidth: 200, // 抽屉宽    drawerPosition: 'left', // 抽屉在左边还是右边    // contentComponent: CustomDrawerContentComponent,  // 自定义抽屉组件    contentOptions: {        initialRouteName: 'Home', // 默认页面组件        activeItemKey : 'Notifications',        labelStyle : {//标签样式            // color : 'red',            height : 30,        },        activeTintColor: 'white',  // 选中文字颜色        activeBackgroundColor: '#ff8500', // 选中背景颜色        inactiveTintColor: '#666',  // 未选中文字颜色        inactiveBackgroundColor: '#fff', // 未选中背景颜色        style: {  // 样式            marginVertical: 0,        },        //没有作用        onItemPress : (route) => {            console.log('-------->' + JSON.stringify(route))        },    },    contentComponent: props => {        console.log('contentComponent');        console.log(props);        return (            <ScrollView>                <View>                    <View style={{paddingVertical: 20, paddingHorizontal: 15, backgroundColor:'#000'}}>                        <Text style={{color:'#FFF'}}>ser Name</Text>                    </View>                    <DrawerItems {...props} />                </View>            </ScrollView>        )    },});const styles = StyleSheet.create({    icon: {        width: 24,        height: 24,    },});export default class MyFirstProjectDemo extends Component {    static navigationOptions = {        // headerTitle: '首页',        // headerLeft:null,//设置左端返回按钮未空        header:null,//隐藏顶部标题栏    };    render() {        return (            <MyFirstProject />        );    }}// export default MyFirstProjectDemo;
定义方式和StackNavigator基本类似,不再赘述。



四、自定义react-navigation


(1)适配顶部导航栏标题:
   测试中发现,在iphone上标题栏的标题为居中状态,而在Android上则是居左对齐。所以需要我们修改源码,进行适配。
【node_modules -- react-navigation -- src -- views -- Header.js】的326行代码处,修改为如下:
[html] view plain copy
  1. title: {  
  2.    bottom: 0,  
  3.    left: TITLE_OFFSET,  
  4.    right: TITLE_OFFSET,  
  5.    top: 0,  
  6.    position: 'absolute',  
  7.    alignItems: 'center',  
  8.  }  

上面方法通过修改源码的方式其实略有弊端,毕竟扩展性不好。还有另外一种方式就是,在navigationOptions中设置headerTitleStyle的alignSelf为 ' center '即可解决。


(2)去除返回键文字显示:

【node_modules -- react-navigation -- src -- views -- HeaderBackButton.js】的91行代码处,修改为如下即可。
[html] view plain copy
  1. {Platform.OS === 'ios' &&  
  2.      title &&  
  3.      <Text  
  4.        onLayout={this._onTextLayout}  
  5.        style={[styles.title, { color: tintColor }]}  
  6.        numberOfLines={1}  
  7.      >  
  8.        {backButtonTitle}  
  9.      </Text>}  

将上述代码删除即可。


(3)动态设置头部按钮事件:

当我们在头部设置左右按钮时,肯定避免不了要设置按钮的单击事件,但是此时会有一个问题,navigationOptions是被修饰为static类型的,所以我们在按钮的onPress的方法中不能直接通过this来调用Component中的方法。如何解决呢?在官方文档中,作者给出利用设置params的思想来动态设置头部标题。那么我们可以利用这种方式,将单击回调函数以参数的方式传递到params,然后在navigationOption中利用navigation来取出设置到onPress即可:

[html] view plain copy
  1. componentDidMount () {  
  2.     /**  
  3.      * 将单击回调函数作为参数传递  
  4.      */  
  5.     this.props.navigation.setParams({  
  6.             switch: () => this.switchView()  
  7.     });  
  8. }  
[html] view plain copy
  1. /**  
  2.  * 切换视图  
  3.  */  
  4. switchView() {  
  5.     alert('切换')  
  6. }  
[html] view plain copy
  1. static navigationOptions = ({navigation,screenProps}) => ({  
  2.     headerTitle: '企业服务',  
  3.     headerTitleStyle: CommonStyles.headerTitleStyle,  
  4.     headerRight: (  
  5.         <NavigatorItem icon={ Images.ic_navigator } onPress={ ()=> navigation.state.params.switch() }/>  
  6.     ),  
  7.     headerStyle: CommonStyles.headerStyle  
  8. });  

(4)结合BackHandler处理返回和点击返回键两次退出App效果

点击返回键两次退出App效果的需求屡见不鲜。相信很多人在react-navigation下实现该功能都遇到了很多问题,例如,其他界面不能返回。也就是手机本身返回事件在react-navigation之前拦截了。如何结合react-natigation实现呢?和大家分享两种实现方式:

(1)在注册StackNavigator的界面中,注册BackHandler:

[java] view plain copy
  1. componentWillMount(){  
  2.     BackHandler.addEventListener('hardwareBackPress'this._onBackAndroid );  
  3. }  
  4.   
  5.   
  6. componentUnWillMount(){  
  7.     BackHandler.addEventListener('hardwareBackPress'this._onBackAndroid);  
  8. }  
  9.   
  10. _onBackAndroid=()=>{  
  11.     let now = new Date().getTime();  
  12.     if(now - lastBackPressed < 2500) {  
  13.         return false;  
  14.     }  
  15.     lastBackPressed = now;  
  16.     ToastAndroid.show('再点击一次退出应用',ToastAndroid.SHORT);  
  17.     return true;  
  18. }  

(2)监听react-navigation的Router

[java] view plain copy
  1. /** 
  2.  * 处理安卓返回键 
  3.  */  
  4. const defaultStateAction = AppNavigator.router.getStateForAction;  
  5. AppNavigator.router.getStateForAction = (action,state) => {  
  6.     if(state && action.type === NavigationActions.BACK && state.routes.length === 1) {  
  7.         if (lastBackPressed + 2000 < Date.now()) {  
  8.             ToastAndroid.show(Constant.hint_exit,ToastAndroid.SHORT);  
  9.             lastBackPressed = Date.now();  
  10.             const routes = [...state.routes];  
  11.             return {  
  12.                 ...state,  
  13.                 ...state.routes,  
  14.                 index: routes.length - 1,  
  15.             };  
  16.         }  
  17.     }  
  18.     return defaultStateAction(action,state);  
  19. };  

(5)实现Android中界面跳转左右切换动画

react-navigation在android中默认的界面切换动画是上下。如何实现左右切换呢?很简单的配置即可:

[java] view plain copy
  1. import CardStackStyleInterpolator from 'react-navigation/src/views/CardStackStyleInterpolator';  
然后在StackNavigator的配置下添加如下代码:

[java] view plain copy
  1. transitionConfig:()=>({  
  2.     screenInterpolator: CardStackStyleInterpolator.forHorizontal,  
  3. })  

(6)解决快速点击多次跳转

当我们快速点击跳转时,会开启多个重复的界面,如何解决呢。其实在官方Git中也有提示,解决这个问题需要修改react-navigation源码:

找到scr文件夹中的addNavigationHelpers.js文件,替换为如下文本即可:

[java] view plain copy
  1. export default function<S: *>(navigation: NavigationProp<S, NavigationAction>) {  
  2.   // 添加点击判断  
  3.   let debounce = true;  
  4.   return {  
  5.       ...navigation,  
  6.       goBack: (key?: ?string): boolean =>  
  7.           navigation.dispatch(  
  8.               NavigationActions.back({  
  9.                   key: key === undefined ? navigation.state.key : key,  
  10.               }),  
  11.           ),  
  12.       navigate: (routeName: string,  
  13.                  params?: NavigationParams,  
  14.                  action?: NavigationAction,): boolean => {  
  15.           if (debounce) {  
  16.               debounce = false;  
  17.               navigation.dispatch(  
  18.                   NavigationActions.navigate({  
  19.                       routeName,  
  20.                       params,  
  21.                       action,  
  22.                   }),  
  23.               );  
  24.               setTimeout(  
  25.                   () => {  
  26.                       debounce = true;  
  27.                   },  
  28.               500,  
  29.               );  
  30.               return true;  
  31.           }  
  32.           return false;  
  33.       },  
  34.     /** 
  35.      * For updating current route params. For example the nav bar title and 
  36.      * buttons are based on the route params. 
  37.      * This means `setParams` can be used to update nav bar for example. 
  38.      */  
  39.     setParams: (params: NavigationParams): boolean =>  
  40.       navigation.dispatch(  
  41.         NavigationActions.setParams({  
  42.           params,  
  43.           key: navigation.state.key,  
  44.         }),  
  45.       ),  
  46.   };  
  47. }  


五、效果图


抽屉导航:


  


以上就是我们实战中常用的属性和技巧。具体的操作还需要大家在实践过程中测试体会。
原创粉丝点击