大家都知道,在 react-native 中若要使用導(dǎo)航的話,有兩種選擇:
- Navigator
- NavigatorIOS
從 API 的寫法上也能夠看出來,NavigatorIOS 只針對 iOS 平臺有限,那么在開發(fā)中,若要兼容 iOS 與 Android 兩個(gè)平臺的話,選擇 NavigatorIOS 就不是那么明智了。當(dāng)然了,在使用方面,NavigatorIOS 會(huì)更加方便和具體,在 UI 和 屬性 設(shè)置方面更加接近 iOS
在這里針對 Navigator 的使用做一些記錄。
render() {
return (
<Navigator initialRoute={{
title: '30 days if RN',
index: 0,
display: true,
component: MainView,
}}
configureScene={this.configureScene}
renderScene={(route, navigator) => {
return <route.component navigator={navigator} title={route.title} index={route.index} />
}}
navigationBar={
<NavigationBar routeMapper={this.routeMapper} style={styles.navBar} />
} />
);
}
從上面的代碼中可以看出使用了 Navigator 的幾大要素:
-
initialRoute: 定義啟動(dòng)時(shí)加載的路由, 與
initialRouteStack二者之中必須要實(shí)現(xiàn)一個(gè)。 -
configureScene: 用來配置場景動(dòng)畫和手勢??蛇x,默認(rèn)為
Navigator.SceneConfigs.PushFromRight。 - renderScene: 必要參數(shù)。用來渲染指定路由的場景。調(diào)用的參數(shù)是路由和導(dǎo)航器。
- ** navigationBar**: 導(dǎo)航欄,可選。
這里主要對導(dǎo)航欄的實(shí)現(xiàn)提供兩種方式:
-
直接在
Navigator里配置navigatorBar屬性:這時(shí)候要配置routeMapper,routeMapper是一個(gè)對象,屬性名必須是LeftButton,RightButton,Title。class NavigationBar extends Navigator.NavigationBar { render() { let routes = this.props.navState.routeStack; if (routes.length) { let route = routes[routes.length -1]; if (route.display === false) { return null; } } return super.render(); } } // 從這個(gè) class 中可以看出,navigationBar 屬性已經(jīng)幫我們實(shí)現(xiàn)了一個(gè)導(dǎo)航欄了,如果不想要的話,可以直接返回 null。 routeMapper = { LeftButton: (route, navigator, index, navState) => { if (route.index > 0) { return ( <TouchableOpacity underlayColor='transparent' onPress={() => {if (index > 0) {navigator.pop()}}}> <Text style={styles.navBackBtn}><Icon size={15} name='ios-arrow-back'></Icon> Back</Text> </TouchableOpacity> ); } else { return null } }, RightButton: (route, navigator, index, navState) => { return null; }, Title: (route, navigator, index, navState) => { return (<Text style={styles.navTitle}>{route.title}</Text>); } }; -
不提供
navigationBar,這樣實(shí)際上是沒有導(dǎo)航欄的,但是我們可以在每個(gè)頁面單獨(dú)配置自己的 “導(dǎo)航欄”。export default class Header extends Component { render() { let obj = this.props.initObj; return ( <View style={[styles.header, styles.row, styles.center]}> <TouchableOpacity style={[styles.row]} onPress={() => this._pop()}> <Icon /> <Text style={styles.fontFFF}>{obj.backName}</Text> </TouchableOpacity> <View style={[styles.title, styles.center]}> <Text style={[styles.fontFFF, styles.titlePos]} numberOfLines={1}>{obj.title}</Text> </View> </View> ); } _pop() { this.props.navigator.pop(); } }
上面的代碼是將頭部封裝起來,然后在需要應(yīng)用的頁面直接使用:
<Header navigator={this.props.navigator} initObj={{backName: '圖書', title: this.state.data.title}} />
參考這里。