首页 > 解决方案 > 如何为特定路线指定自定义转换,而不是屏幕(v5)

问题描述

关于反应导航 v5 的问题。

在以前的版本中,我们可以通过在 a 中执行以下操作来为特定路由指定自定义转换,而不是屏幕StackNavigator

      transitionConfig: () => ({
         screenInterpolator: sceneProps => {
         const {scenes, scene} = sceneProps;
         const prevRoute = scenes[0].route.routeName === 'Route A'; 
         // If prev route is A, and then current route is B, then we do a specific transition
         if (prevRoute && scene.route.routeName === 'Route B') { 
          return StackViewStyleInterpolator.forVertical(sceneProps);
         }
         // Otherwise default to normal transition
         return StackViewStyleInterpolator.forHorizontal(sceneProps);
        },
      }),

现在,我正在尝试为 react-navigation v5 实现相同的目标。我知道我可以通过执行以下操作指定每个屏幕的自定义动画:

<Stack.Screen name="Route B" component={RouteB} options={{ cardStyleInterpolator: CardStyleInterpolators.forVerticalIOS }} />

问题是我不希望每次导航到 时都应用此转换RouteB,仅当上一条路线为 时RouteA,我希望应用此转换,就像上面的前一个代码块一样。

在文档中找不到任何示例,因此希望能在将代码迁移到 v5 方面提供一些帮助。

标签: react-navigationreact-navigation-stackreact-navigation-v5

解决方案


像这样的东西应该工作:

options={({ navigation, route }) => {
  const state = navigation.dangerouslyGetState();
  const index = state.routes.indexOf(route);
  const previousRoute = state.routes[index - 1];

  if (previousRoute?.name === 'RouteA') {
    return {
      cardStyleInterpolator: CardStyleInterpolators.forVerticalIOS,
      gestureDirection: 'vertical',
    };
  } else {
    return {};
  }
}}

推荐阅读