React Native - 导航未定义

React Native - navigation is undefined

我在 App.js

中声明了“ProfileScreen”
function App({ navigation }) {
return (
    <>
    <StatusBar hidden />
    <NavigationContainer>
    <Stack.Navigator initialRouteName="Home">
        
        <Stack.Screen 
        ...            
        component={HomeScreen} 
        ...
        />

        <Stack.Screen 
        ...
        component={FeedScreen}
        ...
        />

        <Stack.Screen 
        ... 
        component={ProfileScreen} 
        ...
        />

    </Stack.Navigator>
    </NavigationContainer>
    </>
);
}

我在里面访问 ProfileScreen FeedScreen.js

export const ProfileScreen = () => {
return(
  <Text style={{ textAlign: "left", color: "black", fontSize: 24, fontFamily: 'Montserrat_100Thin_Italic' }}>
    Hello
  </Text>
);
}

在 FeedScreen.js 我想导航到 ProfileScreen:

const Item = ({ item }, { navigation }) => {
return (
  <>
    <TouchableOpacity onPress={() => navigation.navigate("ProfileScreen")}>
      <Text style={{ textAlign: "left", color: "white", fontSize: 24, fontFamily: 'Montserrat_100Thin_Italic' }}>
        <Image
          style={{ alignSelf: "center", borderRadius: 50 }}
          source={{ uri: item.profile_picture, width: 48, height: 48 }}
        />
        {item.username}
      </Text>
    </TouchableOpacity>
  </>
);
};

不幸的是,一切returns 未定义都不是对象(正在评估'navigation.navigate')

一个简单的解决方案是在你的 Item 组件中使用挂钩 useNavigation,如下所示:

import { useNavigation } from '@react-navigation/native'; 

const Item = ({item}) => {
  const navigation = useNavigation();
  return (
    <TouchableOpacity onPress={() => navigation.navigate('ProfileScreen')}>
      <Text
        style={{
          textAlign: 'left',
          color: 'white',
          fontSize: 24,
          fontFamily: 'Montserrat_100Thin_Italic',
        }}>
        <Image
          style={{alignSelf: 'center', borderRadius: 50}}
          source={{uri: item.profile_picture, width: 48, height: 48}}
        />
        {item.username}
      </Text>
    </TouchableOpacity>
  );
};

你在 FeedScreen 中使用 navigation 属性的语法错误 应该是这样

const Item = ({ item , navigation }) => {