2018.02.09更新:
react-navigation內(nèi)置跳轉(zhuǎn)動(dòng)畫的路徑發(fā)生了改變,由
react-navigation/src/views/CardStackStyleInterpolator 改為
react-navigation/src/views/CardStack/CardStackStyleInterpolator
---------------------------------------------- 分割線 ----------------------------------------------
使用StackNavigator跳轉(zhuǎn)頁面時(shí),react-navigation根據(jù)平臺(tái)的不同內(nèi)置了相應(yīng)的跳轉(zhuǎn)動(dòng)畫。
內(nèi)置的跳轉(zhuǎn)動(dòng)畫在react-navigation/src/views/CardStack/CardStackStyleInterpolator中,共三種。forHorizontal:從右向左進(jìn)入、forVertical:從下向上進(jìn)入、forFadeFromBottomAndroid:從底部淡出。
關(guān)于修改默認(rèn)的跳轉(zhuǎn)動(dòng)畫或者自定義動(dòng)畫效果,以下給出兩個(gè)場(chǎng)景。
修改整個(gè)棧內(nèi)的頁面跳轉(zhuǎn)動(dòng)畫
這種場(chǎng)景是,一個(gè)棧內(nèi)所有頁面的跳轉(zhuǎn)使用相同的動(dòng)畫效果,示例代碼如下:
import CardStackStyleInterpolator from 'react-navigation/src/views/CardStack/CardStackStyleInterpolator';
const CustomerNavigator = StackNavigator({
ScreenKey: { screen: MyScreen },
// other screens
}, {
transitionConfig: () => {
screenInterpolator: CardStackStyleInterpolator.forVertical,
transitionSpec: {
duration: 250,
easing: Easing.bounce,
timing: Animated.timing,
},
},
});
在安卓上運(yùn)行時(shí),默認(rèn)的跳轉(zhuǎn)動(dòng)畫效果是forFadeFromBottomAndroid,經(jīng)過上述配置,CustomerNavigator 內(nèi)的頁面切換時(shí),會(huì)使用forVertical效果。
transitionSpec內(nèi)可以配置與動(dòng)畫相關(guān)的屬性。
通過傳遞參數(shù)決定某頁面的跳轉(zhuǎn)動(dòng)畫
在一個(gè)StackNavigator內(nèi),可能某些頁面需要用forHorizontal的跳轉(zhuǎn)方式,另一些需要用forVertical的跳轉(zhuǎn)方式,以下是解決方案。
import CardStackStyleInterpolator from 'react-navigation/src/views/CardStack/CardStackStyleInterpolator';
const TransitionConfiguration = () => ({
screenInterpolator: (sceneProps) => {
const { scene } = sceneProps;
const { route } = scene;
const params = route.params || {};
const transition = params.transition || 'forHorizontal';
return CardStackStyleInterpolator[transition](sceneProps);
},
});
const CustomerNavigator = StackNavigator({
ScreenKey: { screen: MyScreen },
// other screens
}, {
transitionConfig: TransitionConfiguration,
});
假如希望CustomerNavigator內(nèi)的某個(gè)頁面使用forVertical的跳轉(zhuǎn)動(dòng)畫效果,調(diào)用this.props.navigate('SomeScreenKey', { transition: 'forVertical' });切換頁面即可。
總結(jié)
本文均使用react-navigation自帶的跳轉(zhuǎn)動(dòng)畫,因?yàn)檫@三種跳轉(zhuǎn)方式可以滿足很多需求,希望將來能內(nèi)置更豐富的效果。
react-navigation支持自定義的跳轉(zhuǎn)動(dòng)畫效果,獲取sceneProps中的layout,position,scene屬性,以及scene中的index屬性,就能完成自定義動(dòng)畫的開發(fā)。具體可以參考這篇文章的內(nèi)容。如果想對(duì)其動(dòng)畫原理有更深的了解,可以學(xué)習(xí)這篇文章。
參考資料
- React Native Navigation, custom Scene (Screen) Transitions and interpolations
- issue#1187--Add support for custom transitionConfig
原博文發(fā)布在個(gè)人博客,歡迎訪問??!