案例:列表页跳转详情页
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
NavigatorIOS,
ScrollView
} from 'react-native';
class Detail extends Component {
render() {
return (
<ScrollView>
<Text>详情页</Text>
<Text>尽管信息很少,但这就是详情页</Text>
</ScrollView>
);
}
}
class List extends Component {
goTo() {
this.props.navigator.push({
component: Detail,
title: '邮轮详情',
rightButtonTitle: '购物车',
onRightButtonPress: ()=>{
alert('进入我的购物车');
}
});
}
render() {
return (
<ScrollView>
<Text onPress={this.goTo.bind(this)} style={styles.font}>☆ 豪华邮轮济州岛3日游</Text>
<Text onPress={this.goTo.bind(this)} style={styles.font}>☆ 豪华邮轮台湾3日游</Text>
<Text onPress={this.goTo.bind(this)} style={styles.font}>☆ 豪华邮轮地中海8日游</Text>
</ScrollView>
);
}
}
export default class NavigationDemo extends Component {
render() {
return (
<NavigatorIOS
style={styles.flex}
initialRoute={{
component: List,
title: '邮轮'
}}
/>
);
}
}
const styles = StyleSheet.create({
font: {
fontSize: 16,
lineHeight:25,
marginLeft:10,
marginRight:10
},
flex: {
flex: 1,
marginTop: 25
}
});
AppRegistry.registerComponent('NavigationDemo', () => NavigationDemo);
关于事件中的 this
正确的写法:
<Text onPress={this.goTo.bind(this)} style={styles.font}>☆ 豪华邮轮济州岛3日游</Text>
错误的写法:
<Text onPress={this.goTo} style={styles.font}>☆ 豪华邮轮济州岛3日游</Text>
在 React.js 调用你所传给它的方法的时候,并不是通过对象方法的方式调用(this.goTo),而是直接通过函数调用 (goTo),所以事件监听函数内并不能通过 this 获取到实例(List 组件)。
如果你想在事件函数当中使用当前的实例,你需要手动地将实例方法 bind 到当前实例上再传入给 React.js。bind 会把实例方法绑定到当前实例上,然后我们再把绑定后的函数传给 React.js 的 onPress 事件监听。
React.js 的事件监听方法需要手动 bind 到当前实例,这种模式在 React.js 中非常常用。
总结:
NavigationDemo 组件调用 List 组件,List 组件调用 Detail 组件,它们之间形成链式关系,所有的路由都被 navigator.push 到一个路由数组中,navigator 对象对路由进行控制和跳转。
效果图:

