![](/img/trans.png)
[英]How can i fix this error undefined is not an object(evaluating'navigation.Navigate')?
[英]How can I fix the "undefined is not an object (evaluating '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';
如果您在您定義的“屏幕”之一(主頁、個人資料、音樂)中,React-Navigation 庫會將“導航”道具傳遞給它們。 所以你應該像下面這樣使用它:
props.navigation.navigate('Music');
如果這也失敗了,您可以使用react navigation Hooks來訪問導航對象,如下所示:
import { useNavigation } from '@react-navigation/native';
const MyComponent = () => {
const navigation = useNavigation();
...
return(
...
<Button title="Go to music" onPress={() => { navigation.navigate('Music'); }} />
);
};
export default MyComponent;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.