无法导航到另一个组件 - >错误:无法读取undefined的属性'navigate'

问题描述 投票:1回答:1

在我的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';

我怎样才能解决我的问题?

javascript react-native react-navigation
1个回答
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导入到堆栈导航器页面

希望这将解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.