使用ReactNative 用NavigatorIOS做跳轉時,遇到報錯:
undefined is not an object(evaluating 'this.props.navigator')
代碼如下:
/**
* 003.網易新聞
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
NavigatorIOS,
ScrollView,
Text,
} from 'react-native';
// 遊輪列表
class List extends React.Component {
render() {
return (
<ScrollView style={styles.flex}>
<Text style={styles.list_item} onPress={this.goTo.bind(this)}>✨ 豪華遊輪濟州島</Text>
<Text style={styles.list_item} onPress={this.goTo.bind(this)}>✨ 豪華遊輪太平島</Text>
<Text style={styles.list_item} onPress={this.goTo.bind(this)}>✨ 豪華遊輪釣魚島</Text>
</ScrollView>
);
}
goTo() {
this.props.navigator.push({
component: Detail,
title: '遊輪詳情',
rightButtonTitle: '購物車',
onRightButtonPress: function() {
alert('進入購物車!');
}
});
}
}
// 遊輪詳細信息
class Detail extends React.Component {
render() {
return (
<ScrollView>
<Text style={styles.detail_text}>詳情頁面</Text>
<Text style={styles.detail_text}>詳情信息介紹</Text>
</ScrollView>
);
}
}
class App extends React.Component {
render() {
return (
<NavigatorIOS
style={styles.flex}
initialRoute={{
component: List,
title: '遊輪',
passProps: {},
}}
>
</NavigatorIOS>
);
}
}
const styles = StyleSheet.create({
flex: {
flex: 1,
},
list_item: {
fontSize: 16,
color: 'red',
},
detail_text: {
fontSize: 18,
color: 'blue',
}
});
AppRegistry.registerComponent('AwesomeProject', () => App);
解決辦法:把
onPress={this.goTo}
換成
onPress={this.goTo.bind(this)}
即可