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

man*_*sim 8 javascript navigator ios react-native

我试图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;
Run Code Online (Sandbox Code Playgroud)

然后在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;
Run Code Online (Sandbox Code Playgroud)

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

"Error: undefined is not an object (evaluating 'this.props.navigator')
Run Code Online (Sandbox Code Playgroud)

所以它似乎找不到navigator来自道具但导航器应该通过NavigatorIOS

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

在此输入图像描述

任何提示?

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

Dav*_*ski 20

由于您使用的是ES6,因此需要绑定"this".

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

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

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