代码之家  ›  专栏  ›  技术社区  ›  gigapico00

React Native-导航未定义

  •  0
  • gigapico00  · 技术社区  · 2 年前

    我在应用程序中声明了“ProfileScreen”。js

    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>
        </>
    );
    }
    

    我进入FeedScreen内的ProfileScreen。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>
      </>
    );
    };
    

    不幸的是,一切都回来了 Undefined不是对象(正在评估“navigation.navigate”)

    2 回复  |  直到 2 年前
        1
  •  1
  •   Martinez    2 年前

    要获得简单的解决方案,请使用挂钩 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>
      );
    };
    
        2
  •  1
  •   Inder    2 年前

    您使用的语法错误 navigation 里面的支柱 FeedScreen 应该是这样的

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