簡體   English   中英

React Native,NavigatorIOS,undefined不是一個對象(評估'this.props.navigator.push')

[英]React Native, NavigatorIOS, undefined is not an object (evaluating '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')

所以它似乎無法從道具中找到navigator但導航器應該通過NavigatorIOS傳遞?

此外, Home組件似乎有this.props.navigator根據圖像:

在此輸入圖像描述

任何提示?

我找到了幾個鏈接(人們有完全相同的問題,但沒有幫助):

由於您使用的是ES6,因此需要綁定“this”。

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

編輯:然而,這我一直在使用最近的另一種方式是對函數本身使用箭頭功能,因為它們會自動綁定外部this

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

您可以在constructor函數中將函數綁定到this。

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>
    );
}

這樣做的好處是可以多次使用,也可以清理渲染方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM