开发者问题收集

react-native:无法读取未定义的属性“navigate”

2017-08-31
1906

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

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

无法读取未定义的属性“navigate”

在此行:

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个回答

我遇到了同样的问题。我解决了。试试这个方法。 我在子组件中添加了以下行。

import { withNavigation } from 'react-navigation';

export default withNavigation(ChildComponent_Name);

您可以在 https://reactnavigation.org/docs/en/navigation-prop.html

找到更多详细信息
Chanaka
2018-12-11