如何为特定路由指定自定义转换,而不是屏幕 (v5)
How to specify custom transitions for specific routes, not screens (v5)
关于 react-navigation v5 的问题
在以前的版本中,我们能够通过在 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 方面提供一些帮助。
像这样的东西应该可以工作:
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 {};
}
}}
关于 react-navigation v5 的问题
在以前的版本中,我们能够通过在 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 方面提供一些帮助。
像这样的东西应该可以工作:
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 {};
}
}}