Перейти к содержимому

11. Stack Navigator

Stack Navigator — навигация “стопкой” экранов. Каждый новый экран накладывается поверх. Кнопка “Назад” возвращает к предыдущему.

Окно терминала
npx expo install @react-navigation/native-stack
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
function AppNavigator() {
return (
<Stack.Navigator
initialRouteName="Home"
screenOptions={{
headerStyle: { backgroundColor: '#1e1e2e' },
headerTintColor: '#cba6f7',
headerTitleStyle: { fontWeight: 'bold' },
contentStyle: { backgroundColor: '#1e1e2e' },
}}
>
<Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Главная' }} />
<Stack.Screen
name="Details"
component={DetailsScreen}
options={({ route }) => ({ title: route.params.title })}
/>
<Stack.Screen
name="Modal"
component={ModalScreen}
options={{ presentation: 'modal', animation: 'slide_from_bottom' }}
/>
</Stack.Navigator>
);
}
// iOS-стиль (slide from right) — дефолт
options={{ animation: 'slide_from_right' }}
// Модальный (снизу вверх)
options={{ presentation: 'modal', animation: 'slide_from_bottom' }}
// Fade
options={{ animation: 'fade' }}
// Прозрачный (для кастомных модалок)
options={{ presentation: 'transparentModal' }}
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={{
headerTitle: () => (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<Image source={{ uri: avatarUrl }} style={{ width: 30, height: 30, borderRadius: 15 }} />
<Text style={{ color: '#cdd6f4', fontWeight: 'bold' }}>Профиль</Text>
</View>
),
headerRight: () => (
<TouchableOpacity onPress={handleEdit}>
<Text style={{ color: '#cba6f7' }}>Изменить</Text>
</TouchableOpacity>
),
headerBackVisible: false,
}}
/>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ headerShown: false }}
/>
const navigation = useNavigation();
navigation.navigate('Details'); // Перейти
navigation.push('Details'); // Добавить в стек (даже если уже есть)
navigation.goBack(); // Назад
navigation.popToTop(); // К первому экрану
navigation.reset({ index: 0, routes: [{ name: 'Home' }] }); // Сбросить стек
navigation.replace('Login'); // Заменить текущий экран
export type RootStackParamList = {
Home: undefined;
Details: { id: number; title?: string };
Profile: { userId: string };
};
const Stack = createNativeStackNavigator<RootStackParamList>();
// app.json
{ "expo": { "scheme": "myapp" } }
const linking = {
prefixes: ['myapp://'],
config: {
screens: {
Home: '',
Details: 'details/:id',
Profile: 'profile/:userId',
},
},
};
<NavigationContainer linking={linking}>