React Navigation V3 обрабатывает переходы и анимацию при переходе на другую страницу - PullRequest
0 голосов
/ 15 февраля 2019

Я сейчас использую реагировать-навигация-v3 , который является последним.Я пробовал это решение .Но у меня это не сработало.

Вот переход, который я пытался воспроизвести из решения в ссылке.

const Transition = (index, position) => {
    const inputRange = [index - 1, index, index + 1];
    const opacity = position.interpolate({
        inputRange,
        outputRange: [.8, 1, 1],
    });

    const scaleY = position.interpolate({
        inputRange,
        outputRange: ([0.8, 1, 1]),
    });

    return {
        opacity,
        transform: [
            {scaleY}
        ]
    };
};

, а вот transitionConfig, который яобъявил.

const TransitionConfiguration = () => {
    return {
        // Define scene interpolation, eq. custom transition
        screenInterpolator: (sceneProps) => {

            const {position, scene} = sceneProps;
            const {index, route} = scene
            const params = route.params || {}; // <- That's new
            const transition = params.transition || 'default'; // <- That's new

            return {
                transition: Transition(index, position),
                default: Transition(index, position),
            }[transition];
        }
    }
};

И вот весь список маршрутов :

const UnauthenticatedScreens = createStackNavigator(
    { // Screens
        Login: { screen: Login }
    }
);


const AuthenticatedInitialScreens = createStackNavigator(
    { // Screens
        Home: {
            screen: Home
        },
    }, { // Default options
        defaultNavigationOptions: ({ navigation }) => {
            return {
                header:
                    <DrawerHeader // Default header component
                        headerTitle={navigation.state.routeName}
                        icon="menu"
                        onPress={() => navigation.openDrawer()}
                    />
            };
        }
    }
);

const AppDrawerNavigator = createDrawerNavigator(
    { // Screens
        Home: AuthenticatedInitialScreens,
    }, { // Default options
        initialRouteName: 'Home',
        contentComponent: DrawerComponent, // Default drawer component
        contentOptions: {
            activeTintColor: COLOR.PANTOME
        }
    }
);

const AppSwitchNavigator = createSwitchNavigator(
    { // Screens
        Splash: { screen: Splash },
        UnauthenticatedScreens: { screen: UnauthenticatedScreens },
        AuthenticatedInitialScreens: { screen: AppDrawerNavigator }
    }, { // Default options
        initialRouteName: 'Splash',
        transitionConfig: TransitionConfiguration
    }
);

const AppContainer = createAppContainer(AppSwitchNavigator);

export default AppContainer

и в моем Splash компоненте в componentDidMount метод.

componentDidMount() {
        this.props.actions.restoreSession();
        setTimeout(() => {
            this.props.state.isAuth
                ? this.props.navigation.navigate({
                    params: {
                        transition: 'transition'
                    }
                })
                : this.props.navigation.navigate({
                    routeName: 'UnauthenticatedScreens',
                    params: {
                        transition: 'transition'
                    }
                })
        }, 2000);
    }

Благодарим вас за помощь.Заранее спасибо.

1 Ответ

0 голосов
/ 21 марта 2019

Я смог сделать это, выполнив некоторую условную логику, мы находимся на react-navigation 3.3.2.Также

Вы должны импортировать Easing и Animated из react-native, а затем вы можете условно отображать переходы для определенного экрана по имени или по индексу (ниже по имени).

Объявляя config за пределами навигатором, и переключая transitionSpec с {}, он будет срабатывать только на этом конкретном экране - то же самое с условным для screenInterpolator.

Screen1 до Screen2 имеет анимацию, но ни один из других экранов не имеет этой анимации.

const screen2Config = {
  duration: 300,
  easing: Easing.out(Easing.poly(4)),
  timing: Animated.timing,
};

export const ScreenStack = createStackNavigator({
  Screen1: {
    screen: Screen1,
    navigationOptions: ({ navigation }) => ({
      headerTitle: 'Screen1',
      headerTitleAllowFontScaling: false,
    }),
  },
  Screen2: {
    screen: Screen2,
    navigationOptions: ({ navigation }) => ({
      headerTitle: 'Screen2',
      headerTitleAllowFontScaling: false,
      tabBarVisible: false,
    }),
  },
  Screen3: {
    screen: Screen3,
    navigationOptions: ({ navigation }) => ({
      headerTitle: 'Screen3',
      headerTitleAllowFontScaling: false,
    }),
  },
  Screen4: {
    screen: Screen4,
    navigationOptions: ({ navigation }) => ({
      headerTitle: 'Screen4',
      headerTitleAllowFontScaling: false,
    }),
  },
}, {
  headerMode: 'float',
  mode: 'modal',
  transitionConfig: sceneProps => ({
    transitionSpec: sceneProps.scene.route.routeName === 'Screen2' ? screen2Config : {},
    screenInterpolator: (sceneProps) => {
      if (sceneProps.scene.route.routeName === 'Screen2') {
        const { layout, position, scene } = sceneProps;
        const { index } = scene;

        const width = layout.initWidth;
        const translateX = position.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [width, 0, 0],
        });

        const opacity = position.interpolate({
          inputRange: [index - 1, index - 0.99, index],
          outputRange: [0, 1, 1],
        });

        return { opacity, transform: [{ translateX }] };
      }
    },
  }),
});
...