屏幕頁面間的導航跳轉
移動app很少是由單一的頁面組成的。管理多個頁面間的呈現和過渡是navigator導航器所必須要處理的一個任務。
這篇文章覆蓋了在React Native中的大部分導航組件。如果你對導航也是一知半解,或者說剛入門,你可以嘗試使用React Navigation這個npm包。該包提供了一種簡單易用的導航方式,可以同時滿足對stack navigation和tabbed navigation兩種導航模式,並且兼容IOS和Android。而且這都是使用Javascript實現的,方便和狀態管理的libraries例如redux做適配。
如果你只是想針對IOS,你當然可以使用NavigatorIOS。這個組件能夠提供你想要的原生的樣子,而且配置最少。爲什麼呢,因爲這個組件就是基於IOS中的UINavigationController這個類來封裝的。所以說啦,這個組件在Android上沒法用。
如果你想要在IOS和Android上同時實現一種native的原生效果,或者說你想要把React Native切入到原本就是用原生實現的app中,那麼下面的這兩個包可以滿足你的要求:native-navigation和react-native-navigation.
React Navigation
這個包的是一個獨立得library,而且是由社區貢獻的,可以實現僅僅通過幾行配置代碼就能夠建立app中的頁面跳轉。
安裝的第一步就是在你的項目中執行以下代碼:
npm install --save react-navigation
然後你可以很快的創建一個app,並且設置它的首頁和介紹頁面:
import {
createStackNavigator,
} from 'react-navigation';
const App = createStackNavigator({
Home: { screen: HomeScreen },
Profile: { screen: ProfileScreen },
});
export default App;
每個頁面組件都可以設置很多的導航選項,例如標題名稱啊。也可以使用navigation props上的的action creator來鏈到其他頁面。
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
const { navigate } = this.props.navigation;
return (
<Button
title="Go to Jane's profile"
onPress={() =>
navigate('Profile', { name: 'Jane' })
}
/>
);
}
}
React Navigation的router路由的是非常方便用來複寫導航邏輯或者直接整合到Redux中。因爲路由router本身就死可以嵌套的,所以說呢開發者完全可以只改寫app中的某一塊區域的導航邏輯而不做全局的修改。
React Navigation中的視圖可以使用原生的組件,並且動畫庫的話也可以傳遞60fps的動畫到運行native線程的設備上。另一個好處是動畫和手勢的配置非常容易。
如果想要完全瞭解React Navigation,可以看下React Navigation的Getting Started Guide,或者看下其他的類似文檔,Intro to Navigators。
NavigatorIOS
NavigatorIOS 看上去或是感覺上像是UINavigationController,沒錯,因爲這就是構建在這之上的。
<NavigatorIOS
initialRoute={{
component: MyScene,
title: 'My Initial Scene',
passProps: {myProp: 'foo'},
}}
/>
就像其他的導航系統,NavigatorIOS使用路由來代表頁面(screens),不過還是有些許不同。想要渲染哪個組件,通過路由上的組件key值就可以,另外任何想要傳遞給該組件的參數的話都可以通過passProps來實現。一個“navigator”的對象會自動作爲一個參數傳遞給組件,這樣你就可以按需調用push或是pop。
當NavigatorIOS使用原生的UIKit導航的時候,它將自動渲染一個導航條,順便會帶上一個返回按鈕和一個標題。
import React from 'react';
import PropTypes from 'prop-types';
import {Button, NavigatorIOS, Text, View} from 'react-native';
export default class NavigatorIOSApp extends React.Component {
render() {
return (
<NavigatorIOS
initialRoute={{
component: MyScene,
title: 'My Initial Scene',
passProps: {index: 1},
}}
style={{flex: 1}}
/>
);
}
}
class MyScene extends React.Component {
static propTypes = {
route: PropTypes.shape({
title: PropTypes.string.isRequired,
}),
navigator: PropTypes.object.isRequired,
};
constructor(props, context) {
super(props, context);
this._onForward = this._onForward.bind(this);
}
_onForward() {
let nextIndex = ++this.props.index;
this.props.navigator.push({
component: MyScene,
title: 'Scene ' + nextIndex,
passProps: {index: nextIndex},
});
}
render() {
return (
<View>
<Text>Current Scene: {this.props.title}</Text>
<Button
onPress={this._onForward}
title="Tap me to load the next scene"
/>
</View>
);
}
}
如果想要了解更多關於該組件的內容可以查看NavigatorIOS的參考文檔。