导航时导航未定义

时间:2018-04-05 06:04:44

标签: react-native react-navigation

我正试图从一个组件导航到另一个组件。我得到的错误是按下:

  

undefined不是评估this.props.navigation.navigate

的对象

header.js

import React, { Component } from "react";
import { View, Text, StyleSheet, Button, Image } from "react-native";
import Icon from "react-native-vector-icons/FontAwesome";


export default class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }



  render() {
    return (

        <View style={styles.container}>

        <View style = {{ flex: 1 , flexDirection :"row"}} >

        <Icon name="align-justify" size={30} color="#fff" 

        style= {{ paddingLeft : 20, paddingTop:20 , alignSelf: 'flex-start',}}

        onPress = { () => this.props.navigation.navigate('Notifications') }

        />

        <Text style={styles.Text}> {this.props.title} </Text>

        </View>

        </View>

        );
  }
}

const styles = StyleSheet.create({
  container: {
    width: "100%",
    height: 70,
    flexDirection: "row",
    backgroundColor: "#3498db",
    justifyContent: "center"
  },
  Text: {
    color: "#fff",
    fontSize: 20,
    fontWeight: "bold",
    alignSelf: "center",
    paddingLeft: 20
  }
});

navigation.js

import React from 'react';
import { Platform} from "react-native";
import Icon from "react-native-vector-icons";
import { StackNavigator, NavigationActions, DrawerNavigator } from 'react-navigation';

import LoginScreen from '../components/loginScreen';
import RegisterScreen from '../components/registerScreen';
import HomeScreen from "../components/HomeScreen";
import NotificationsScreen from "../components/NotificationsScreen";

const HomeStack = DrawerNavigator(
  {
    Home: {
      screen: HomeScreen,
      navigationOptions: { drawerLabel: "Home" }
    },

    Notifications: {
      screen: NotificationsScreen,
      navigationOptions: { drawerLabel: "Notifications" }
    }
  },
  {
    gesturesEnabled: false
  }
);



const MainNavigation = StackNavigator(
  {
    Home: {
      screen: HomeStack,
    },
    Login: {
      screen: LoginScreen,
      navigationOptions: { gesturesEnabled: false }
    },
    Register: {
      screen: RegisterScreen,
      navigationOptions: { gesturesEnabled: false }
    }
  },
  {
    transitionConfig: () => ({ screenInterpolator: () => null }),
    headerMode: "none",
    initialRouteName: "Login",
    navigationOptions: { gesturesEnabled: false }
  }
);


export default MainNavigation;

2 个答案:

答案 0 :(得分:1)

只有您直接链接到屏幕的组件才会获得this.props.navigation.navigate

屏幕内的子元素无法获得this.props.navigation.navigate.

假设您在HomeScreen中。你可以在这里使用this.props.navigation。但是如果你在HomeScreen中使用Header作为子组件,那么你必须明确地传递为

<Header navigation={this.props.navigation} />

答案 1 :(得分:0)

您在哪个文件中调用MainNavigation?

为了将naivagation作为道具,你需要在MainNavigation Component中包装你的App组件。 这样的事情。

<App>
<MainNavigation/>
</App>