天天看點

react-navigation 使用詳解一、開源庫介紹二、react-navigation使用三、DrawerNavigator實作抽屜導航五、效果圖

一、開源庫介紹

今年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擴充功能

1、StackNavigator屬性介紹

navigationOptions:配置StackNavigator的一些屬性。
 
    title:标題,如果設定了這個導航欄和标簽欄的title就會變成一樣的,不推薦使用
    header:可以設定一些導航的屬性,如果隐藏頂部導航欄隻要将這個屬性設定為null
    headerTitle:設定導航欄标題,推薦
    headerBackTitle:設定跳轉頁面左側傳回箭頭後面的文字,預設是上一個頁面的标題。可以自定義,也可以設定為null
    headerTruncatedBackTitle:設定當上個頁面标題不符合傳回箭頭後的文字時,預設改成"傳回"
    headerRight:設定導覽列右側。可以是按鈕或者其他視圖控件
    headerLeft:設定導覽列左側。可以是按鈕或者其他視圖控件
    headerStyle:設定導覽列的樣式。背景色,寬高等
    headerTitleStyle:設定導航欄文字樣式
    headerBackTitleStyle:設定導航欄‘傳回’文字樣式
    headerTintColor:設定導航欄顔色
    headerPressColorAndroid:安卓獨有的設定顔色紋理,需要安卓版本大于5.0
    gesturesEnabled:是否支援滑動傳回手勢,iOS預設支援,安卓預設關閉
 
 
screen:對應界面名稱,需要填入import之後的頁面
 
mode:定義跳轉風格
 
   card:使用iOS和安卓預設的風格
 
   modal:iOS獨有的使螢幕從底部畫出。類似iOS的present效果
 
headerMode:傳回上級頁面時動畫效果
 
   float:iOS預設的效果
 
   screen:滑動過程中,整個頁面都會傳回
 
   none:無動畫
 
cardStyle:自定義設定跳轉效果
 
   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的前景色 不活躍狀态下
 
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
 
     drawerWidth - 抽屜的寬度
     drawerPosition - 選項是左或右。 預設為左側位置
     contentComponent - 用于呈現抽屜内容的元件,例如導航項。 接收抽屜的導航。 預設為DrawerItems
     contentOptions - 配置抽屜内容
 
     initialRouteName - 初始路由的routeName
     order - 定義抽屜項目順序的routeNames數組。
     路徑 - 提供routeName到路徑配置的映射,它覆寫routeConfigs中設定的路徑。
     backBehavior - 後退按鈕是否會切換到初始路由? 如果是,設定為initialRoute,否則為none。 預設為initialRoute行為
 
    DrawerItems的contentOptions屬性
 
     activeTintColor - 活動标簽的标簽和圖示顔色
     activeBackgroundColor - 活動标簽的背景顔色
     inactiveTintColor - 非活動标簽的标簽和圖示顔色
     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/[email protected]')}
            selectedImage={require('./imgs/[email protected]')}
          />
        )
      }),
    },
 
    Mine:{
          screen:MineScreen,
          navigationOptions:({navigation}) => ({
          tabBarLabel:'我',
          tabBarIcon:({focused,tintColor}) => (
            <TabBarItem
             tintColor={tintColor}
              focused={focused}
              normalImage={require('./imgs/[email protected]')}
              selectedImage={require('./imgs/[email protected]')}
            />
          )
        }),
      },
    },
 
    {
      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 使用詳解一、開源庫介紹二、react-navigation使用三、DrawerNavigator實作抽屜導航五、效果圖

以上就是我們實戰中常用的屬性和技巧。具體的操作還需要大家在實踐過程中測試體會。