我正在创建一个名为HomeIcon
的组件,并通过header
> defaultNavigationOptions
将其插入我的headerRight
,我在此组件中添加了一个onPress
,指定this.props.navigation.navigate('Main');
的目的是单击此组件加载MainScreen
但是当我单击上面标题中描述的错误时发生。这是代码:
import React from 'react';
import { StyleSheet, TouchableOpacity, Image, Dimensions } from 'react-native';
export default class HomeIcon extends React.Component {
render() {
return (
<TouchableOpacity onPress={() => {
this.props.navigation.navigate('Main');
}}>
<Image style={styles.buttonHome} source={require('../icons/home2.png')} />
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
buttonHome: {
aspectRatio: 1,
resizeMode: 'contain',
height: Dimensions.get('window').width * 0.08,
width: Dimensions.get('window').height * 0.08,
margin: Dimensions.get('window').height * 0.018
}
});
import React from 'react';
import { createAppContainer, createStackNavigator } from 'react-navigation';
import Main from './source/screens/MainScreen';
import CustomCards from './source/screens/CustomCardsScreen';
import HomeIcon from './source/components/HomeIcon';
const AppNavigator = createStackNavigator ({
'Main': {
screen: Main,
navigationOptions: {
title: 'Tela Principal'
}
},
'CustomCards': {
screen: CustomCards,
navigationOptions: {
title: 'Cartões Personalizados'
}
}
}, {
defaultNavigationOptions: {
headerTitleStyle: {
flexGrow: 1,
fontWeight: 'bold',
textAlign: 'center'
},
headerLeft: (null),
headerRight: (
<HomeIcon />
),
headerStyle:{
backgroundColor: '#7d253b'
},
headerTintColor: '#FFF'
}
});
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"eject": "expo eject"
},
"dependencies": {
"@types/react": "^16.8.13",
"@types/react-native": "^0.57.43",
"expo": "^32.0.0",
"react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"react-navigation": "^3.6.1"
},
"devDependencies": {
"babel-preset-expo": "^5.0.0"
},
"private": true
}
访问GitHub中的项目存储库以获取更多详细信息:https://github.com/Alex-Xavier/ACTIFICA
defaultNavigationOptions = ({ navigation }) => ({
headerTitleStyle: {
flexGrow: 1,
fontWeight: 'bold',
textAlign: 'center',
},
headerLeft: (null),
headerRight: (
<HomeIcon navigation={navigation} />
),
headerStyle: {
backgroundColor: '#7d253b',
},
headerTintColor: '#FFF',
});
您需要将导航对象传递给该组件。 'this.props.navigation'仅在直接分配给堆栈/标签/抽屉导航的屏幕中可用。在你的情况下它的屏幕'主'和'CustomCards'
HomeIcon组件不知道this.props.navigation是什么。
你必须将'导航'作为道具传递。像这样:
headerRight: ({ navigation }) => <HomeIcon navigation={navigation}/>
然后在你的HomeIcon中,它将以this.props.navigation的形式提供。