在React Navigation中,你可以通过传递参数从堆栈导航器(Stack Navigator)导航到选项卡导航器(Tab Navigator)。以下是一个示例,展示如何实现这一点。
首先,确保你已经安装了React Navigation及其所需的依赖项。
npm install @react-navigation/native
npm install @react-navigation/stack
npm install @react-navigation/bottom-tabs
npm install react-native-screens react-native-safe-area-context
在你的主文件(例如 App.js
)中,设置导航容器并配置堆栈导航器和选项卡导航器。
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { Button, Text, View } from 'react-native';
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Tabs"
onPress={() => navigation.navigate('Tabs', { screen: 'Tab1', params: { userId: 123 } })}
/>
</View>
);
}
function Tab1Screen({ route }) {
const { userId } = route.params;
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Tab 1 Screen</Text>
<Text>User ID: {userId}</Text>
</View>
);
}
function Tab2Screen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Tab 2 Screen</Text>
</View>
);
}
function Tabs() {
return (
<Tab.Navigator>
<Tab.Screen name="Tab1" component={Tab1Screen} />
<Tab.Screen name="Tab2" component={Tab2Screen} />
</Tab.Navigator>
);
}
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Tabs" component={Tabs} />
</Stack.Navigator>
</NavigationContainer>
);
}
Tab1Screen
和 Tab2Screen
。在 HomeScreen
中,使用 navigation.navigate
方法导航到选项卡导航器,并传递参数:
onPress={() => navigation.navigate('Tabs', { screen: 'Tab1', params: { userId: 123 } })}
在 Tab1Screen
中,通过 route.params
获取传递的参数:
const { userId } = route.params;
领取专属 10元无门槛券
手把手带您无忧上云