尝试导航到另一个屏幕时收到错误“未定义不是评估this.props.navigation的对象”

时间:2019-01-17 11:45:14

标签: react-native react-navigation expo

在尝试使用切换导航进行导航时返回此错误。

我尝试删除此内容。然后道具返回未定义的“导航”。

import React from 'react';
import { Text, View, Image, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { createSwitchNavigator, createAppContainer , withNavigation } from 'react-navigation';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import layout from '../../constants/LayoutStyle'
import QuoteScreen from './QuoteScreen';

 const HomeScreen = () => {

 return (
           <View style={styles.viewStyles}>
           <View style={{position: 'absolute',top: hp('50%')+wp('37.5%'),left:wp('15%'),width: wp('32.5%'),height: 
      wp('32.5%'),backgroundColor:'rgba(255,255,255,0.1)'}}>
            <View style={{alignItems: 'center',justifyContent: 'center',flex:1}}>
            <Icon name="ios-book" color="purple" size={wp('10%')}
              onPress={() => this.props.navigation.navigate('Quote')}
              />
            <Text style={styles.tabTextStyle}>Books</Text>
            </View>
  </View>

    );
 };

 const RootStack = createSwitchNavigator(
  {
     Home: HomeScreen,
     Quote: QuoteScreen,
   }
 );

  const AppContainer = createAppContainer(RootStack);

  export default class app extends React.Component {
    render() {
      return <AppContainer />
    }
  }

预计将正确完成导航

1 个答案:

答案 0 :(得分:2)

主屏幕是一个功能组件,因此,您不应该使用this.props.navigation,而只需说props.navigation。

如果要在功能组件内部使用props,则use应该将props作为参数传递给该功能组件。像这样=>

 const HomeScreen = (props) => {
    return (
       <View style={styles.viewStyles}>
       <View style={{position: 'absolute',top: 
          hp('50%')+wp('37.5%'),left:wp('15%'),width: wp('32.5%'),height: 
  wp('32.5%'),backgroundColor:'rgba(255,255,255,0.1)'}}>
        <View style={{alignItems: 'center',justifyContent: 'center',flex:1}}>
        <Icon name="ios-book" color="purple" size={wp('10%')}
          onPress={() => this.props.navigation.navigate('Quote')}
          />
        <Text style={styles.tabTextStyle}>Books</Text>
        </View>
   </View>
   );
};

如果这不起作用,则在您使用的任何地方将导航作为道具传递给 HomeScreen 组件,就像这样=>

<HomeScreen 
  navigation = {this.props.navigation} // or navigation = {props.navigation}, if it is functional component
/>