【问题标题】:Is there a way to chain navigation in React Navigation V5?有没有办法在 React Navigation V5 中链接导航?
【发布时间】:2021-10-01 13:00:59
【问题描述】:

假设我有屏幕 A、B、C。是否可以在屏幕 A 中编写代码以从 A 导航到 B,然后立即导航到 C?

【问题讨论】:

    标签: react-native react-navigation react-navigation-v5


    【解决方案1】:

    使用dispatchCustom action creators

    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,
          });
        });
      }
    

    全码试吃零食here.

    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;
    
    
    结果

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2021-03-05
      • 2011-10-21
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2020-12-06
      • 1970-01-01
      相关资源
      最近更新 更多