Navigation undefined - TypeError: undefined is not an object (evaluating 'navigation.navigate')

Navigation undefined - TypeError: undefined is not an object (evaluating 'navigation.navigate')

我在使用主屏幕上 header 按钮的导航道具时遇到问题。看来问题是无法呈现 Navaigation 道具。有人可以帮我解决这个问题吗?我花了很多时间阅读该文档,但无法更进一步。谢谢!

import * as React from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import Home from '../screens/Shop/Home';
import ProductDetails from '../screens/Shop/ProductDetails';
import Colors from '../constants/Colors';
import {Ionicons} from '@expo/vector-icons';
import {
  HeaderButtons,
  HeaderButton,
  Item,
} from 'react-navigation-header-buttons';
import Cart from '../screens/Shop/Cart';
import {NavigationContainer, useNavigation} from '@react-navigation/native';

const IoniconsHeaderButton = (props) => (
  <HeaderButton
    IconComponent={Ionicons}
    iconSize={23}
    color="white"
    {...props}
  />
);

const Stack = createStackNavigator();

export default ShopNavigator = ({navigation}) => {
  return (
    <Stack.Navigator
      screenOptions={{
        headerStyle: {
          backgroundColor: Colors.accent,
        },
        headerTintColor: 'white',
        headerTitleStyle: {
          fontFamily: 'balsamiq-regular',
        },
      }}
    >
      <Stack.Screen
        name="Home"
        component={Home}
        options={{
          headerRight: () => (
            <HeaderButtons HeaderButtonComponent={IoniconsHeaderButton}>
              <Item
                title="search"
                iconName="cart-outline"
                onPress={() => navigation.navigate('Cart')}
              />
            </HeaderButtons>
          ),
        }}
      />
      <Stack.Screen
        name="ProductDetails"
        component={ProductDetails}
        options={({route}) => ({title: route.params.itemTitle})}
      />
      <Stack.Screen name="Cart" component={Cart} />
    </Stack.Navigator>
  );
};

基本上,您只是没有传递选项返回的导航参数。这就是未定义错误的原因

改变这个

  options={{
          headerRight: () => (
            <HeaderButtons HeaderButtonComponent={IoniconsHeaderButton}>
              <Item
                title="search"
                iconName="cart-outline"
                onPress={() => navigation.navigate('Cart')}
              />
            </HeaderButtons>
          ),
        }}

至此

   options={({ navigation }) => ({
        headerRight: () => (
          <HeaderButtons HeaderButtonComponent={IoniconsHeaderButton}>
            <Item
              title="search"
              iconName="cart-outline"
              onPress={() => navigation.navigate('Cart')}
            />
          </HeaderButtons>
        ),
      })}