当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React Native react-navigation 导航使用详解

React Native react-navigation 导航使用详解

2017年12月08日  | 移动技术网IT编程  | 我要评论

一、开源库介绍

今年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属性介绍
navigationoptions:配置stacknavigator的一些属性。  

  1. title:标题,如果设置了这个导航栏和标签栏的title就会变成一样的,不推荐使用 
  2. header:可以设置一些导航的属性,如果隐藏顶部导航栏只要将这个属性设置为null 
  3. headertitle:设置导航栏标题,推荐 
  4. headerbacktitle:设置跳转页面左侧返回箭头后面的文字,默认是上一个页面的标题。可以自定义,也可以设置为null 
  5. headertruncatedbacktitle:设置当上个页面标题不符合返回箭头后的文字时,默认改成"返回" 
  6. headerright:设置导航条右侧。可以是按钮或者其他视图控件 
  7. headerleft:设置导航条左侧。可以是按钮或者其他视图控件 
  8. headerstyle:设置导航条的样式。背景色,宽高等 
  9. headertitlestyle:设置导航栏文字样式 
  10. headerbacktitlestyle:设置导航栏‘返回'文字样式 
  11. headertintcolor:设置导航栏颜色 
  12. headerpresscolorandroid:安卓独有的设置颜色纹理,需要安卓版本大于5.0 
  13. gesturesenabled:是否支持滑动返回手势,ios默认支持,安卓默认关闭  

screen:对应界面名称,需要填入import之后的页面  

mode:定义跳转风格  

card:使用ios和安卓默认的风格  

modal:ios独有的使屏幕从底部画出。类似ios的present效果  

headermode:返回上级页面时动画效果  

float:ios默认的效果  

screen:滑动过程中,整个页面都会返回   

none:无动画  

cardstyle:自定义设置跳转效果  

  1. transitionconfig: 自定义设置滑动返回的配置  
  2. ontransitionstart:当转换动画即将开始时被调用的功能  
  3. ontransitionend:当转换动画完成,将被调用的功能  

path:路由中设置的路径的覆盖映射配置  

initialroutename:设置默认的页面组件,必须是上面已注册的页面组件  

initialrouteparams:初始路由参数 

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

2、tabnavigator属性介绍

screen:和导航的功能是一样的,对应界面名称,可以在其他页面通过这个screen传值和跳转。  

navigationoptions:配置tabnavigator的一些属性  

title:标题,会同时设置导航条和标签栏的title  

tabbarvisible:是否隐藏标签栏。默认不隐藏(true)  

tabbaricon:设置标签栏的图标。需要给每个都设置  

tabbarlabel:设置标签栏的title。推荐  

导航栏配置   

tabbarposition:设置tabbar的位置,ios默认在底部,安卓默认在顶部。(属性值:'top','bottom')  

swipeenabled:是否允许在标签之间进行滑动  

animationenabled:是否在更改标签时显示动画  

lazy:是否根据需要懒惰呈现标签,而不是提前,意思是在app打开的时候将底部标签栏全部加载,默认false,推荐为true  

trueinitialroutename: 设置默认的页面组件  

backbehavior:按 back 键是否跳转到第一个tab(首页), none 为不跳转  

tabbaroptions:配置标签栏的一些属性ios属性  

activetintcolor:label和icon的前景色 活跃状态下  

activebackgroundcolor:label和icon的背景色 活跃状态下  

inactivetintcolor:label和icon的前景色 不活跃状态下  

inactivebackgroundcolor:label和icon的背景色 不活跃状态下  

showlabel:是否显示label,默认开启 style:tabbar的样式  

labelstyle:label的样式安卓属性  

activetintcolor:label和icon的前景色 活跃状态下  

inactivetintcolor:label和icon的前景色 不活跃状态下  

showicon:是否显示图标,默认关闭  

showlabel:是否显示label,默认开启 style:tabbar的样式  

labelstyle:label的样式 uppercaselabel:是否使标签大写,默认为true  

presscolor:material涟漪效果的颜色(安卓版本需要大于5.0)  

pressopacity:按压标签的透明度变化(安卓版本需要小于5.0)  

scrollenabled:是否启用可滚动选项卡 tabstyle:tab的样式  

indicatorstyle:标签指示器的样式对象(选项卡底部的行)。安卓底部会多出一条线,可以将height设置为0来暂时解决这个问题  

labelstyle:label的样式  

iconstyle:图标样式 

3、drawernavigator属性介绍

drawernavigatorconfig  

  1. drawerwidth - 抽屉的宽度 
  2. drawerposition - 选项是左或右。 默认为左侧位置 
  3. contentcomponent - 用于呈现抽屉内容的组件,例如导航项。 接收抽屉的导航。 默认为draweritems 
  4. contentoptions - 配置抽屉内容  

initialroutename - 初始路由的routename  

order - 定义抽屉项目顺序的routenames数组。  

路径 - 提供routename到路径配置的映射,它覆盖routeconfigs中设置的路径。  

backbehavior - 后退按钮是否会切换到初始路由? 如果是,设置为initialroute,否则为none。 默认为initialroute行为  

draweritems的contentoptions属性  

  1. activetintcolor - 活动标签的标签和图标颜色  
  2. activebackgroundcolor - 活动标签的背景颜色  
  3. inactivetintcolor - 非活动标签的标签和图标颜色  
  4. inactivebackgroundcolor - 非活动标签的背景颜色  

内容部分的样式样式对象 

labelstyle - 当您的标签是字符串时,要覆盖内容部分中的文本样式的样式对象 
从上述中大致了解了react-navigation三种组件的一些基本属性,所以到我们甩起袖子撸代码见证下奇迹了。

4、使用stacknavigator + tabnavigator实现tab界面切换、界面间导航

api定义:stacknavigator(routeconfigs, stacknavigatorconfig)、tabnavigator(routeconfigs, tabnavigatorconfig)

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

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

import {stacknavigator,tabnavigator,tabbarbottom} from 'react-navigation'; 
import homescreen from './pages/homepage'; 
import minescreen from './pages/minepage'; 

(3)定义tabnavigator:

const tab = tabnavigator( 
 { 
  home:{ 
   screen:homescreen, 
   navigationoptions:({navigation}) => ({ 
    tabbarlabel:'首页', 
    tabbaricon:({focused,tintcolor}) => ( 
     <tabbaritem 
      tintcolor={tintcolor} 
      focused={focused} 
      normalimage={require('./imgs/nav_fav@2x.png')} 
      selectedimage={require('./imgs/nav_fav_actived@3x.png')} 
     /> 
    ) 
   }), 
  }, 
 
  mine:{ 
     screen:minescreen, 
     navigationoptions:({navigation}) => ({ 
     tabbarlabel:'我', 
     tabbaricon:({focused,tintcolor}) => ( 
      <tabbaritem 
       tintcolor={tintcolor} 
       focused={focused} 
       normalimage={require('./imgs/tab_me_nor@3x.png')} 
       selectedimage={require('./imgs/tab_me_selected@2x.png')} 
      /> 
     ) 
    }), 
   }, 
  }, 
 
  { 
   tabbarcomponent:tabbarbottom, 
   tabbarposition:'bottom', 
   swipeenabled:false, 
   animationenabled:false, 
   lazy:true, 
   tabbaroptions:{ 
    activetintcolor:'#06c1ae', 
    inactivetintcolor:'#979797', 
    style:{backgroundcolor:'#ffffff',}, 
    labelstyle: { 
       fontsize: 20, // 文字大小 
     }, 
   } 
    
  } 
 
 ); 

tabbaritem为封装的组件:

import react,{component} from 'react'; 
import {image} from 'react-native'; 
 
export default class tabbaritem extends component { 
 
  render() { 
    return( 
      <image source={ this.props.focused ? this.props.selectedimage : this.props.normalimage } 
        style={ { tintcolor:this.props.tintcolor,width:25,height:25 } } 
      /> 
    ) 
  } 
   
} 

可以看到,我们定义了一个名称为【tab】的tabnavigator的导航组件。在组件中,分为两层参数:

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

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

tabnavigator定义好之后,需要用stacknavigator,顾名思义,stacknavigator就是以栈的方式来存放整个界面的,而

tabnavigator是作为一个界面内不同子界面之间切换。所以还需要我们定义stacknavigator:

const navigator = stacknavigator( 
  
 { 
  tab:{screen:tab}, 
  product:{screen:productscreen} 
 }, 
 
 { 
  navigationoptions:{ 
   headerbacktitle:null, 
   headertintcolor:'#333333', 
   showicon:true, 
   swipeenabled:false, 
   animationenabled:false, 
  }, 
 
  mode:'card', 
 }); 

看起来和tabnavigator很相似,同样是指定了两个参数:

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

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

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

最后就是在render中引用stacknavigator:

export default class demo extends component { 
 
 render() { 
    return ( 
     <navigator /> 
    ); 
 } 
} 

stacknavigator还提供了onnavigationstatechange回调方法,用来监听导航状态的改变。具体不再赘述。实现了界面跳转和切换,那么就该来增加下界面之间的感情了,来看看如何实现界面之间的传值和取值。

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

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

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

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

this.props.navigation.navigate('mine'); 

参数为我们在stacknavigator注册界面组件时的名称。同样也可以从当前页面返回到上一页:

// 返回上一页 
this.props.navigation.goback(); 

(2)跳转时传值:

this.props.navigation.navigate('mine',{info:'传值过去'}); 

第一个参数同样为要跳转的界面组件名称,第二个参数为要传递的参数,info可以理解为key,后面即传递的参数。

(3)获取值:

{this.props.navigation.state.params.info} 

通过state.params来获取传来的参数,后面为key值。此处为info。

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

三、drawernavigator实现抽屉导航

1、导航实现

api定义:drawernavigator(routeconfigs,drawernavigatorconfig)

(1)界面中定义drawernavigator:

import {stacknavigator,tabnavigator,drawernavigator} from 'react-navigation'; 
import homescreen from './pages/homepage'; 
import minescreen from './pages/minepage'; 
 
export default class demo extends component { 
 
 render() { 
    return ( 
     <navigator /> 
    ); 
 } 
} 
 
const navigator = drawernavigator({ 
 
  home:{screen:homescreen}, 
  mine:{screen:minescreen}, 
}); 
 
const styles = stylesheet.create({ 
 
  container: { 
    flex: 1, 
  }, 
}); 
 
appregistry.registercomponent('demo', () => demo); 

定义方式和stacknavigator基本类似,不再赘述。

(2)homescreen界面和minescreen界面:

export default class homepage extends component { 
 
  static navigationoptions = { 
    drawerlabel: '首页', 
    drawericon:({tintcolor}) => ( 
      <image 
        source={require('./../imgs/ic_happy.png')} 
        style={[styles.icon, {tintcolor: tintcolor}]}/> 
    ), 
  }; 
 
  render() { 
    return( 
      <view style={{flex:1}}> 
        <text onpress={this._skip.bind(this)}>点击跳转</text> 
      </view> 
    ); 
  } 
 
  _skip() { 
    this.props.navigation.navigate("mine"); 
  } 
} 
 
 
export default class minepage extends component { 
 
  static navigationoptions = { 
    drawerlabel:'我', 
     drawericon: ({ tintcolor }) => ( 
      <image 
        source={require('./../imgs/ic_h.png')} 
        style={[styles.icon, {tintcolor: tintcolor}]} 
      /> 
    ), 
  }; 
 
  render() { 
    return( 
      <view style={{flex:1}}> 
        <text onpress={this._skip.bind(this)}>返回上一界面</text> 
      </view> 
    ); 
  } 
 
  /** 
   * 跳转 
   */ 
  _skip() { 
    this.props.navigation.goback(); 
  } 
} 

代码很简单,实现了界面之间的跳转。

2、扩展功能

(1)默认drawerview不可滚动。要实现可滚动视图,必须使用contentcomponent自定义容器,如下所示:

{ 
 drawerwidth:200, 
 抽屉位置:“对” 
 contentcomponent:props => <scrollview> <draweritems {... props} /> </ scrollview> 
} 

(2)可以覆盖导航使用的默认组件,使用draweritems自定义导航组件:

import {draweritems} from 'react-navigation'; 
 
const customdrawercontentcomponent = (props) => ( 
 <view style = {style.container}> 
  <draweritems {... props} /> 
 </view>  
); 

(3)嵌套抽屉导航

如果您嵌套drawernavigation,抽屉将显示在父导航下方。

四、自定义react-navigation

(1)适配顶部导航栏标题:

测试中发现,在iphone上标题栏的标题为居中状态,而在android上则是居左对齐。所以需要我们修改源码,进行适配。
【node_modules -- react-navigation -- src -- views -- header.js】的326行代码处,修改为如下:

title: { 
  bottom: 0, 
  left: title_offset, 
  right: title_offset, 
  top: 0, 
  position: 'absolute', 
  alignitems: 'center', 
 } 

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

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

【node_modules -- react-navigation -- src -- views -- headerbackbutton.js】的91行代码处,修改为如下即可。

{platform.os === 'ios' && 
   title && 
   <text 
    onlayout={this._ontextlayout} 
    style={[styles.title, { color: tintcolor }]} 
    numberoflines={1} 
   > 
    {backbuttontitle} 
   </text>} 

将上述代码删除即可。

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

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

componentdidmount () { 
  /** 
   * 将单击回调函数作为参数传递 
   */ 
  this.props.navigation.setparams({ 
      switch: () => this.switchview() 
  }); 
} 
/** 
 * 切换视图 
 */ 
switchview() { 
  alert('切换') 
} 
static navigationoptions = ({navigation,screenprops}) => ({ 
  headertitle: '企业服务', 
  headertitlestyle: commonstyles.headertitlestyle, 
  headerright: ( 
    <navigatoritem icon={ images.ic_navigator } onpress={ ()=> navigation.state.params.switch() }/> 
  ), 
  headerstyle: commonstyles.headerstyle 
}); 

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

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

(1)在注册stacknavigator的界面中,注册backhandler:

componentwillmount(){ 
  backhandler.addeventlistener('hardwarebackpress', this._onbackandroid ); 
} 
 
 
componentunwillmount(){ 
  backhandler.addeventlistener('hardwarebackpress', this._onbackandroid); 
} 
 
_onbackandroid=()=>{ 
  let now = new date().gettime(); 
  if(now - lastbackpressed < 2500) { 
    return false; 
  } 
  lastbackpressed = now; 
  toastandroid.show('再点击一次退出应用',toastandroid.short); 
  return true; 
} 

(2)监听react-navigation的router

/** 
 * 处理安卓返回键 
 */ 
const defaultstateaction = appnavigator.router.getstateforaction; 
appnavigator.router.getstateforaction = (action,state) => { 
  if(state && action.type === navigationactions.back && state.routes.length === 1) { 
    if (lastbackpressed + 2000 < date.now()) { 
      toastandroid.show(constant.hint_exit,toastandroid.short); 
      lastbackpressed = date.now(); 
      const routes = [...state.routes]; 
      return { 
        ...state, 
        ...state.routes, 
        index: routes.length - 1, 
      }; 
    } 
  } 
  return defaultstateaction(action,state); 
}; 

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

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

复制代码 代码如下:

import cardstackstyleinterpolator from 'react-navigation/src/views/cardstackstyleinterpolator'; 

然后在stacknavigator的配置下添加如下代码:

transitionconfig:()=>({ 
  screeninterpolator: cardstackstyleinterpolator.forhorizontal, 
}) 

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

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

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

export default function<s: *>(navigation: navigationprop<s, navigationaction>) { 
 // 添加点击判断 
 let debounce = true; 
 return { 
   ...navigation, 
   goback: (key?: ?string): boolean => 
     navigation.dispatch( 
       navigationactions.back({ 
         key: key === undefined ? navigation.state.key : key, 
       }), 
     ), 
   navigate: (routename: string, 
         params?: navigationparams, 
         action?: navigationaction,): boolean => { 
     if (debounce) { 
       debounce = false; 
       navigation.dispatch( 
         navigationactions.navigate({ 
           routename, 
           params, 
           action, 
         }), 
       ); 
       settimeout( 
         () => { 
           debounce = true; 
         }, 
       500, 
       ); 
       return true; 
     } 
     return false; 
   }, 
  /** 
   * for updating current route params. for example the nav bar title and 
   * buttons are based on the route params. 
   * this means `setparams` can be used to update nav bar for example. 
   */ 
  setparams: (params: navigationparams): boolean => 
   navigation.dispatch( 
    navigationactions.setparams({ 
     params, 
     key: navigation.state.key, 
    }), 
   ), 
 }; 
} 

五、效果图

抽屉导航:

 

以上就是我们实战中常用的属性和技巧。具体的操作还需要大家在实践过程中测试体会。希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网