乐闻世界logo
搜索文章和话题

How to Pass Parameters to screen in StackNavigator?

1个答案

1

In React Navigation, StackNavigator is a commonly used navigation method for navigating between screens and passing parameters. To pass parameters to a specific screen within StackNavigator, follow these steps:

1. Define StackNavigator

First, define the StackNavigator and set up the required screens. For example:

javascript
import { createStackNavigator } from '@react-navigation/stack'; import HomeScreen from './HomeScreen'; import DetailsScreen from './DetailsScreen'; const Stack = createStackNavigator(); function MyStack() { return ( <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Details" component={DetailsScreen} /> </Stack.Navigator> ); }

2. Pass Parameters

When navigating from one screen to another, pass parameters using the second argument of the navigation.navigate method. For example, passing parameters from HomeScreen to DetailsScreen:

javascript
// In HomeScreen navigation.navigate('Details', { itemId: 42, otherParam: 'anything you want here' });

3. Receive Parameters

In the target screen (e.g., DetailsScreen), receive these parameters via the route prop:

javascript
// In DetailsScreen function DetailsScreen({ route, navigation }) { const { itemId, otherParam } = route.params; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Item ID: {itemId}</Text> <Text>Other Param: {otherParam}</Text> <Button title="Go back" onPress={() => navigation.goBack()} /> </View> ); }

Example:

Suppose there is an online store application where a user clicks on a product in HomeScreen. We want to navigate to DetailsScreen and display detailed information about the product. By following the above steps, you can pass parameters between screens to ensure users can view the detailed information of the selected product.

This approach allows you to effectively pass and receive parameters between different screens in StackNavigator, making the application's navigation more flexible and feature-rich.

2024年6月29日 12:07 回复

你的答案