React Native,NavigatorIOS,undefined不是一个对象(评估'this.props.navigator.push')

我试图使用NavigatorIOS所以在我的index.ios.js我得到了:

 'use strict'; var React = require('react-native'); var Home = require('./App/Components/Home'); var { AppRegistry, StyleSheet, NavigatorIOS } = React; var styles = StyleSheet.create({ container:{ flex: 1, backgroundColor: '#111111' } }); class ExampleApp extends React.Component{ render() { return ( <NavigatorIOS style={styles.container} initialRoute={{ title: 'example', component: Home }} /> ); } }; AppRegistry.registerComponent('exampleapp', () => ExampleApp); module.exports = ExampleApp; 

然后在Home.js

 'use strict'; var React = require('react-native'); var Park = require('./Park'); var { View, StyleSheet, Text, TouchableHighlight } = React; var styles = StyleSheet.create({ ... }); class Home extends React.Component{ onPress() { this.props.navigator.push({ title: 'Routed!', component: Park }); } render() { return ( <View style={styles.mainContainer}> <Text> Testing React Native </Text> <TouchableHighlight onPress={this.onPress} style={styles.button}> <Text>Welcome to the NavigatorIOS . Press here!</Text> </TouchableHighlight> </View> ); } }; module.exports = Home; 

我遇到的问题是,当我点击TouchableHighlight触发onPress() ,我得到一个错误:

 "Error: undefined is not an object (evaluating 'this.props.navigator') 

所以它似乎无法从道具中findnavigator ,但导航器应该通过NavigatorIOS

此外,似乎Home组件具有this.props.navigator按图像:

在这里输入图像说明

任何提示?

我发现了几个链接(人们有完全相同的问题,但没有帮助):

  • https://github.com/facebook/react-native/issues/416

  • 未定义不是一个对象(评估“this.props.navigator.push”)

既然你使用ES6,你需要绑定“this”。

例如: onPress={this.onPress.bind(this)}

编辑:另一种我最近使用的方法是在函数本身上使用箭头函数,因为它们会自动绑定到外部。

 onPress = () => { this.props.navigator.push({ title: 'Routed!', component: Park }); }; 

你可以在constructor函数中绑定这个函数。

 constructor(props) { super(props); this.onPress = this.onPress.bind(this); } 

然后在没有绑定的情况下使用它。

 render() { return ( <TouchableHighlight onPress={this.onPress} style={styles.button}> <Text>Welcome to the NavigatorIOS. Press here!</Text> </TouchableHighlight> ); } 

这样做的好处是可以多次使用,并且清理你的渲染方法。