跳到主要内容

Stack Navigator - Move Between Screens

In the previous section Hello React Navigation we defined a stack navigator with two routes Home and Details, but we didn’t know how to let the user go from Home to Details.

If it was a web browser, we could write something like this:

<a href="details.html">Go to Details</a>
<a
onClick={() => {
window.location.href = 'details.html'
}}
>
Go to Details
</a>

We'll do something like this, but instead of using the global window window.location we will use the navigation property that is passed to our screen components.

Go to new screen

App.js
import * as React from 'react'
import { View, Button, Text } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'

const HomeScreen = ({ navigation }) => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button title="Go to Details" onPress={() => navigation.navigate('Details')} />
</View>
)

const DetailsScreen = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
)

const Stack = createStackNavigator()

const App = () => (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
)

export default App

Try this example on Snack

Let's deal with this:

  • navigation - the navigation property is passed to each screen component in the stack navigator.
  • navigate ('Details') - we call the navigate function with the name of the route we would like to navigate the user.
信息

If we call navigation.navigate with a route name that we did not define in the navigator, it will throw an error in development assemblies and nothing will happen in production assemblies. In other words, we can only jump to routes that have been defined in our navigator - we cannot jump to an arbitrary component.

Back button

The header provided by the stack navigator will automatically include a return button when you can return from the active screen. If there is only one screen in the navigation stack, there is nothing to go back to, then there will be no back button.

Sometimes you need to be able to programmatically trigger this behavior, and for that you can use navigation.goBack()

<Button title="Go back" onPress={() => navigation.goBack()} />

Back to top

Sometimes we need to take the user back several screens at once. This is done using navigation.popToTop()

<Button title="Go back to first screen in stack" onPress={() => navigation.popToTop()} />

Done

To see how well you learned this lesson, take the test in our school's mobile app on this topic or in Telegram bot.

EnglishMoji!

React Navigation

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Dmitriy Vasilev

💲

EnglishMoji!