在REACTIVATIONS V5中有没有链接导航的方法? [英] Is there a way to chain navigation in React Navigation V5?

查看:22
本文介绍了在REACTIVATIONS V5中有没有链接导航的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

id="use-dispatch-with-custom-action-creators-kh5d">useCustom 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;

结果

这篇关于在REACTIVATIONS V5中有没有链接导航的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆