React Native Navigation(StackNavigator):我收到错误说" undefined不是一个对象(评估' this.props.navigate')"

时间:2017-11-26 19:24:25

标签: javascript jquery reactjs react-native

我刚刚开始学习反应原生......现在做一个宠物项目.... 在应用程序中,点击它的按钮导航到另一个屏幕。我得到以下错误说" undefined不是一个对象(评估' this.props.navigate')" 以下是文件

index.js

  import React from "react";
  import Navigator from "./config/routes";
  export default () => <Navigator />;

我的config / routes.js中的代码

import { StackNavigator } from "react-navigation";

import Home from "../screens/Home";
import List from "../screens/List";

export default StackNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      header: () => null
    }
  },
  List: {
     screen: List
  }
});

和我的组件文件Home.js,其中包含单击点击导航到另一个屏幕的按钮

 /*all import statements*/
 class Home extends Component {
    handlePressBaseCurrency() {
       console.log("base currency button clicked");
       this.props.navigation.navigate("List"); /* error from this line */
    }
    render() {
            return (
                <UserInput
                    currencyShort={TEMP_BASE_CURRENCY}
                    onPress={this.handlePressBaseCurrency}
                    defaultValue={TEMP_BASE_PRICE}
                    keyboardType="numeric"
                    onChangeText={this.handleTextChange}
                />
            );
        }
 }

请帮忙!!!提前致谢:D

1 个答案:

答案 0 :(得分:0)

this未在handlePressBaseCurrency中正确绑定。你可以:

  1. 在构造函数中显式bind this

    constructor(props) {
      super(props);
      this.handlePressBaseCurrency = this.handlePressBaseCurrency.bind(this);
    }
    
  2. 来自handling events上的React文档:

      

    如果调用bind会让你烦恼,有两种方法可以解决这个问题。如果您使用的是实验public class fields syntax,则可以使用类字段正确绑定回调:

    handlePressBaseCurrency = () => {
      console.log("base currency button clicked");
      this.props.navigation.navigate("List");
    };