无法导航到另一个组件->错误:无法读取未定义的属性“ navigate”

时间:2019-04-16 21:03:35

标签: javascript react-native react-navigation

在我的react native应用中,我有一个header,它包含:


export default class foto extends Component {
.
.
.
.
static navigationOptions = {
        headerTitle: <Titulo/>,
        headerTitleStyle: {
            color: 'white',
        },
        headerRight: <MenuIcon/>,
        headerLeft: <HomeIcon/>,
        headerStyle: {
            backgroundColor: '#d87c3a'
        }
};

}

我想,当我按headerRight导航到某个组件时,问题是当我尝试时会出现一条错误消息:Cannot read property 'navigate' of undefined

<MenuIcon/>default class foto之外,但在同一文件中

MenuIcon代码:

class MenuIcon extends React.Component{
    render(){
        return(
            <TouchableOpacity style={{marginRight:10}}>
                <Icon name={'md-menu'} size={26} color='white'
                onPress={() => this.props.navigation.navigate('menu')}/>
            </TouchableOpacity>
        )
    }
}



我在App.js上的StackNavigator:

const AppNavigator = createStackNavigator({
  login2: {
    screen: Login2
  },
  foto: {
    screen: Foto
  },
  menu: {
    screen: Menu
  }
}, {
    initialRouteName: 'login2',
});




export default createAppContainer(AppNavigator);

我的进口商品:

import React, { Component } from 'react'
import { Text, View, ImageBackground, Image, TextInput, TouchableOpacity, TouchableHighlight, Button } from 'react-native';
import { createStackNavigator, createAppContainer } from "react-navigation";
import AsyncStorage from '@react-native-community/async-storage';
import Icon from 'react-native-vector-icons/Ionicons';

我该如何解决我的问题?

1 个答案:

答案 0 :(得分:0)

您需要将导航传递到<MenuIcon/>,这样导航才能如下:

const AppNavigator = createStackNavigator({
  login2: {
    screen: Login2
  },
  foto: {
    screen: Foto,
    navigationOptions: ({ navigation }) => ({
    headerTitle: <Titulo/>,
    headerTitleStyle: {
        color: 'white',
    },
    headerRight: <MenuIcon navigation={navigation}/>,
    headerLeft: <HomeIcon/>,
    headerStyle: {
        backgroundColor: '#d87c3a'
    }
     })
  },
  menu: {
    screen: Menu
  }
}, {
    initialRouteName: 'login2',
});


export default createAppContainer(AppNavigator);

这应该允许您从MenuIcon组件导航 请注意,您不需要Foto类中的导航选项,并且不要忘记将MenuIcon和HomeIcon都导入到堆栈导航器页面

希望这可以解决您的问题。