react-native:无法读取属性'导航'未定义的

时间:2017-08-31 10:03:08

标签: react-native react-navigation

我使用ActionButton和tabNavigator创建一个组件(MyGlobalComponent),并在其中创建一个stackNavigator。 我在我的app组件中使用了这个组件。

我想通过按ActionButton上的按钮导航到TabNavigator的屏幕,但是我收到此错误:

Cannot read property 'navigate' of undefined

在这一行:

goToCamera = () => { this.props.navigation.navigate("NewObs"); };

这是我的代码:

import React, { Component } from "react";
import { AppRegistry, Text, View, Image, Alert, Platform } from "react-native";
import { StackNavigator, TabNavigator } from "react-navigation";

import Photo from "./Photo";
import NouvelleObservation from "./NouvelleObservation";
import Optionpage from "./Optionpage";

import SettingPage from "./page/Setting";
import LoginPage from "./page/Login";

import styles from "./css/styles";



import ActionButton from "react-native-action-button";
import Icon from "react-native-vector-icons/Ionicons";
import Toolbar from "react-native-toolbar";


const MyTabView = TabNavigator({
  Photo: { screen: Photo },
  NewObs: { screen: NouvelleObservation },
  Options: {
    screen: StackNavigator({
      setting: { screen: SettingPage },
      login: { screen: LoginPage }
    })
  }
});

class MyGlobalComponent extends Component {
  constructor(props) {
    super(props);
  }

  goToCamera = () => {
    this.props.navigation.navigate("NewObs");
  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        <MyTabView />

        <ActionButton
          buttonColor="rgba(231,76,60,1)"
          offsetY={offsetYValue}
          offsetX={10}
        >
          <ActionButton.Item
            buttonColor="#1abc9c"
            title="Go to new obs"
            onPress={() => {
              this.goToCamera();
            }}
          >
            <Icon name="md-camera" style={styles.actionButtonIcon} />
          </ActionButton.Item>
        </ActionButton>
      </View>
    );
  }
}

MyGlobalComponent.router = MyTabView.router;

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
        <View style={styles.maincontainer}>
          <MyGlobalComponent />
        </View>
    );
  }
}

我尝试在每个构造函数中记录props,但我看不到导航。

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我面临同样的问题。我解决了尝试这种方式。 我将以下行添加到子组件。

import { withNavigation } from 'react-navigation';

export default withNavigation(ChildComponent_Name);

您可以找到更多详细信息https://reactnavigation.org/docs/en/navigation-prop.html