React Native Navigation:在另一个文件的函数内部时无法在堆栈之间导航

React Native Navigation : can't navigate between stack when inside a function from another file

感谢 Stephan 的回答,我现在已经能够解决我的问题

我对 导航React Native 中的工作方式有点问题。
基本上我想做的是:\

当我在 Home 堆栈中时,从 Feed[=53= 导航到 SubFeed 堆栈] 在 Home.

中调用的函数

这是我的代码

import Feed from './Feed'

function Home({ navigation }) {

return (
    <ScrollView>
        <Feed/>
    </ScrollView>

Home.js

function Feed({ navigation }) {

return (
    <View>
        <Button title="nav1" 
                onPress={() => navigation.navigate('SubFeed')}/>
        <Button title="nav2" 
                onPress={() => navigation.navigate('Home', {screen: 'SubFeed'})}/>
    </View>

Feed.js

在我的 App.js 中,我创建了这样的堆栈:

<NavigationContainer>
  <StatusBar
    backgroundColor="#ffa31a" />
  <Stack.Navigator initialRouteName="Project">
    <Stack.Screen name="Project" component={Home}/>
    <Stack.Screen name="Feed" component={Feed} />
    <Stack.Screen name="SubFeed" component={SubFeed} />
  </Stack.Navigator>
</NavigationContainer>

App.js

我发现在我使用导航的其他文件中,只要我的函数中有 { navigation },我就不需要导入任何东西来使导航工作。


问题是每当我尝试按下其中一个按钮时,我都会收到相同的错误:

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

当我搜索答案时,我不断看到有关 screens 的信息,但它似乎对我的情况不起作用。

  • 我认为问题出在我试图从家里更改外面的堆栈,但我不明白为什么。

如果您对我的问题有任何建议或更好的答案,我将不胜感激。

在您的代码中,Feed 组件不知道导航 属性。因此,您可以将它作为父 Home 的道具传递,或者您可以使用 react-navigation-hooks 并在 Feed 组件中使用 const { navigate } = useNavigation();