React-Native 的Navigator控制界面跳转

例子:
界面跳转

回顾一下,一个简单的界面包含一下几块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Sample React Native App
* https://github.com/hanks-zyh
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
} = React;
var AwesomeProject = React.createClass({
render: function(){
return (<Text>Hello, hanks</Text>);
}
});
var styles = StyleSheet.create({
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

接下来练习Navigator的使用,Navigator标签负责不同界面之间的跳转;

官方文档

基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<Navigator
initialRoute={{name: 'My First Scene', index: 0}}
renderScene={(route, navigator) =>
<MySceneComponent
name={route.name}
onForward={() => {
var nextIndex = route.index + 1;
navigator.push({
name: 'Scene ' + nextIndex,
index: nextIndex,
});
}}
onBack={() => {
if (route.index > 0) {
navigator.pop();
}
}}
/>
}
/>

基础方法 push, pop, NavigatorrenderScene 方法可以获取到 navigatorroute对象,然后就可使用 navigatorpush, pop 控制界面.

获取 navigatorroute 的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//...
<Navigator
ddebugOverlay={false}
initialRoute={{ title: 'Main', id:'http'}}
configureScence={{ configureScence }}
renderScene={renderSceneAndroid}
/>
var _navigator; //全局navigator对象
//...
renderSceneAndroid: function(route, navigator){
_navigator = navigator;
if(route.id === 'http'){
return (
<HttpView navigator={navigator} route={route} />
);
}
if(route.id === 'shop'){
return (
<ShopView navigator={navigator} route={route}/>
);
}
//...
// 调用push 跳转
<TouchableOpacity onPress={ () => _navigator.push({title:'Http',id:'http'}) } style={ styles.button }>
<Text>NetWork</Text>
</TouchableOpacity>

根据route的id来判断跳到哪个界面, 调用 push 添加新的界面, push的参数为 route:字典

安卓返回按键监听

http.js 中获取 navigator 对象,调用 pop 方法退出界面

1
2
3
4
5
6
7
8
9
10
BackAndroid.addEventListener('hardwareBackPress', function() {
if(_navigator == null){
return false;
}
if(_navigator.getCurrentRoutes().length === 1){
return false;
}
_navigator.pop();
return true;
});

githb源码