#react-native #react-navigation #react-navigation-v5
Вопрос:
Предположим, у меня есть экраны A, B, C. Можно ли написать код на экране A, чтобы перейти от A к B, а затем сразу к C?
Ответ №1:
используйте диспетчеризацию с создателями пользовательских действий
import { CommonActions } from '@react-navigation/native';
const goToC = () => {
navigation.dispatch((state) => {
//update navigation state as you want.
const routes = [
//current state
...state.routes,
//add 2 new route to state.
{ name: 'b', params: {id : 100} }, //you can also add params
{name: 'c' }
];
return CommonActions.reset({
...state,
routes,
index: routes.length - 1,
});
});
}
полный код попробуйте перекусить здесь.
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { CommonActions } from '@react-navigation/native';
const containerStyle = { flex: 1, alignItems: 'center', justifyContent: 'center' };
function ScreenA({ navigation }) {
const goToC = () => {
navigation.dispatch((state) => {
const routes = [
...state.routes,
{ name: 'b', params: {id : 100} },
{name: 'c' }
];
return CommonActions.reset({
...state,
routes,
index: routes.length - 1,
});
});
}
return (
<View style={containerStyle}>
<Text>ScreenA</Text>
<Button
onPress={goToC}
title="Go to C"
/>
</View>
);
}
function ScreenB({ navigation, route }) {
return (
<View style={containerStyle}>
<Text>{JSON.stringify(route.params)}</Text>
<Text>ScreenB</Text>
</View>
)
}
function ScreenC({ navigation }) {
return <View style={containerStyle}><Text>ScreenC</Text></View>
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="a" component={ScreenA} />
<Stack.Screen name="b" component={ScreenB} />
<Stack.Screen name="c" component={ScreenC} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;