首页 > 解决方案 > 如何修复“未定义不是对象(评估'navigation.navigate')”?

问题描述

所以,这是我创建的导航容器:

<NavigationContainer>
        <Stack.Navigator
          screenOptions={{
            headerShown: false
          }}
        >
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Music" component={MusicScreen} />
          <Stack.Screen name="Profile" component={ProfileScreen} />
        </Stack.Navigator>
      </NavigationContainer>

但我不需要每个屏幕上的按钮都是唯一的,将有 3 个按钮显示在所有屏幕上。所以这是我的地图功能,我通过所有按钮进行映射:

{tabs.map(({ icon, line }, index) => (
                <View key={ index }>
                  <Tab 
                    {...{ index, transition, active }}
                    onPress={() => {
                      active.setValue(index);

                      if (index == 0) {
                        navigation.navigate('Music')
                      } else if (index == 1) {
                        navigation.navigate('Home')
                      } else if (index == 2) {
                        navigation.navigate('Profile')
                      }
                    }}
                  >
                    {icon}
                  </Tab>
                  <View style={styles.blueLineContainerBack}>
                    <LineWrapper
                      {...{activeTransition, active, line, index}}
                    />
                  </View>
                </View>
              ))}

当我按下按钮时,我得到 undefined is not an object (evaluating 'navigation.navigate') 错误。我该如何解决?

标签: reactjsreact-nativenavigationreact-navigationscreen

解决方案


需要注意的navigation是,它仅在屏幕组件中定义。在您的 onPress 函数中,调用 useNavigation 挂钩以访问导航。像这样的东西应该工作:

const navigation = useNavigation();

你需要像这样从 React Navigation 导入它:

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


推荐阅读