首頁  >  文章  >  web前端  >  詳細解讀react-navigation的導覽使用

詳細解讀react-navigation的導覽使用

亚连
亚连原創
2018-06-22 18:38:483036瀏覽

本篇文章主要介紹了React Native react-navigation 導航使用詳解,詳解的介紹了react-navigation導航的使用,具有一定的參考價值,有興趣的可以了解一下

#一、開源程式庫介紹

今年1月份,新開源的react-natvigation庫備受矚目。在短短不到3個月的時間,github上星數已達4000 。 Fb建議使用函式庫,並且在React Native目前最新版本0.44中刪除Navigator。 react-navigation據稱有原生般的性能體驗效果。可能會成為未來React Native導航組件的主流軍。本篇內容基於【 ^1.0.0-beta.9 】版本來介紹關於該庫的使用和實戰技巧。可以看到,雖然是beta版本,不過基本上穩定,大家可放心在專案中使用。奉上  react-navigation 官方文件

該函式庫包含三類元件:
(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:設定導覽列'回傳'文字樣式 

    headerBackTitleStyle:設定導覽列'回傳'文字樣式 
  11. headerTintColor:設定導覽列顏色 
  12. headerPressColorAndroid:安卓獨有的設定色彩紋理,需要安卓版本大於5.0 
  13. #gesturesEnabled:是否支援滑動返回手勢,iOS預設支持,安卓預設關閉  

screen:對應介面名稱,需要填入import之後的頁面  

mode :定義跳轉風格  

card:使用iOS和安卓預設的風格  

modal:iOS獨有的使螢幕從底部畫出。類似iOS的present效果  

headerMode:在返回上級頁面時動畫效果  

float:iOS預設的效果  

screen:滑動過程中,整個頁面都會返回   

screen:滑動過程中,整個頁面都會返回   

  1. screen:滑動過程中,整個頁面都會返回   

    none:無動畫  
  2. cardStyle:自訂設定跳轉效果  

  3. transitionConfig: 自訂設定滑動回傳的設定  

  4. transitionConfig: 自訂設定滑動回傳的設定  

onTransitionStart:當轉換動畫即將開始時被呼叫的功能  

#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的前景色不活躍狀態下  

inactiveBackgroundor: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. #activeBackground - 活動標籤標籤的背景顏色  

  3. inactiveTintColor - 非活動標籤的標籤和圖示顏色  

  4. inactiveBackgroundColor - 非活動標籤的背景顏色  

  5. ##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(&#39;./imgs/nav_fav@2x.png&#39;)} 
      selectedImage={require(&#39;./imgs/nav_fav_actived@3x.png&#39;)} 
     /> 
    ) 
   }), 
  }, 
 
  Mine:{ 
     screen:MineScreen, 
     navigationOptions:({navigation}) => ({ 
     tabBarLabel:&#39;我&#39;, 
     tabBarIcon:({focused,tintColor}) => ( 
      <TabBarItem 
       tintColor={tintColor} 
       focused={focused} 
       normalImage={require(&#39;./imgs/tab_me_nor@3x.png&#39;)} 
       selectedImage={require(&#39;./imgs/tab_me_selected@2x.png&#39;)} 
      /> 
     ) 
    }), 
   }, 
  }, 
 
  { 
   tabBarComponent:TabBarBottom, 
   tabBarPosition:&#39;bottom&#39;, 
   swipeEnabled:false, 
   animationEnabled:false, 
   lazy:true, 
   tabBarOptions:{ 
    activeTintColor:&#39;#06c1ae&#39;, 
    inactiveTintColor:&#39;#979797&#39;, 
    style:{backgroundColor:&#39;#ffffff&#39;,}, 
    labelStyle: { 
       fontSize: 20, // 文字大小 
     }, 
   } 
    
  } 
 
 );

TabBarItem為封裝的元件:

import React,{Component} from &#39;react&#39;; 
import {Image} from &#39;react-native&#39;; 
 
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:&#39;#333333&#39;, 
   showIcon:true, 
   swipeEnabled:false, 
   animationEnabled:false, 
  }, 
 
  mode:&#39;card&#39;, 
 });

看起来和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(&#39;Mine&#39;);

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

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

(2)跳转时传值:

this.props.navigation.navigate(&#39;Mine&#39;,{info:&#39;传值过去&#39;});

第一个参数同样为要跳转的界面组件名称,第二个参数为要传递的参数,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: &#39;首页&#39;, 
    drawerIcon:({tintColor}) => ( 
      <Image 
        source={require(&#39;./../imgs/ic_happy.png&#39;)} 
        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:&#39;我&#39;, 
     drawerIcon: ({ tintColor }) => ( 
      <Image 
        source={require(&#39;./../imgs/ic_h.png&#39;)} 
        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 &#39;react-navigation&#39;; 
 
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: &#39;absolute&#39;, 
  alignItems: &#39;center&#39;, 
 }

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

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

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

{Platform.OS === &#39;ios&#39; && 
   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(&#39;切换&#39;) 
}
static navigationOptions = ({navigation,screenProps}) => ({ 
  headerTitle: &#39;企业服务&#39;, 
  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(&#39;hardwareBackPress&#39;, this._onBackAndroid ); 
} 
 
 
componentUnWillMount(){ 
  BackHandler.addEventListener(&#39;hardwareBackPress&#39;, this._onBackAndroid); 
} 
 
_onBackAndroid=()=>{ 
  let now = new Date().getTime(); 
  if(now - lastBackPressed < 2500) { 
    return false; 
  } 
  lastBackPressed = now; 
  ToastAndroid.show(&#39;再点击一次退出应用&#39;,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 &#39;react-navigation/src/views/CardStackStyleInterpolator&#39;;

然后在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, 
    }), 
   ), 
 }; 
}

五、效果图

抽屉导航:

 

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用JS如何实现去除重复json

详细解读vue中的$mount

在vue中如何使用refs定位

在js中如何转换bool值?

以上是詳細解讀react-navigation的導覽使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn