reactjs - 如何修复“未定义不是对象(评估'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') 错误。我该如何解决?
解决方案
需要注意的navigation
是,它仅在屏幕组件中定义。在您的 onPress 函数中,调用 useNavigation 挂钩以访问导航。像这样的东西应该工作:
const navigation = useNavigation();
你需要像这样从 React Navigation 导入它:
import { useNavigation } from '@react-navigation/native';
推荐阅读
- c - 通过引用传递时声明变量的行为是否未定义?
- r - 计算 R 中组和特定列中的唯一计数
- c# - 使用 Dapper 进行弹性查询:过程需要“ntext/nchar/nvarchar”类型的参数
- c# - 写正则表达式 c#
- c - 当输入多于所需的输入时,sscanf 检查不起作用
- sql - Laravel 7 查询关系表
- anzograph - Anzograph - 如何为 5600 配置不同的端口
- javascript - 如何用最新的 Babel + Gulp 替换 @babel/polyfill?
- docker - 如何通过文件名从 docker linux 容器下载文件到客户端文件系统?
- python - Selenium find_elements_by_class_name 未返回完整列表