在我的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';
我该如何解决我的问题?
答案 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都导入到堆栈导航器页面
希望这可以解决您的问题。