React-native-scrollable-tab-view 是rn 開發(fā)里比較方便的tab切換插件。
先上效果圖吧荤西。github地址 :https://github.com/JunIce/react-native-scroll-customTabBar
運行過官方demo的同學都知道卸耘,原來的demo是下面的橫線平分整個盒模型退敦, 如下圖。
可是現實需求不一定是要等分的蚣抗,類似于微博會有這種下邊框帶動效的tab侈百。
分析我們的需求,下邊線由原來的等分變成居中,所以原來的自適應填充就不能使用了钝域,需要我們來定義下邊線的長度讽坏,
this.props.tabUnderlineDefaultWidth ? this.props.tabUnderlineDefaultWidth : containerWidth / (numberOfTabs * 2);
為了達到預期的效果,我這里設置的如果不填寫默認寬度网梢,就默認設置原來tab的一半震缭。
居中效果用絕對定位, 配和計算left值達到居中效果
接下來就是滑動過程中下邊框變長战虏,如果說要js滑動過程計算拣宰,那計算很復雜,所以才用來scaleX這中方式進行變化烦感,達到變長的目的巡社。
const translateX = this.props.scrollValue.interpolate({
? ? ? ? ? ? ? ? ?inputRange: [0, 1],
? ? ? ? ? ? ? ? outputRange: [0, containerWidth / numberOfTabs],
});
我們看原來源碼里的動畫函數,就是scrollValue會傳過來一個動畫對象手趣,0即是開始狀態(tài)晌该,1是結束狀態(tài),結束時移動一個tab的寬度绿渣,inputRange 和?outputRange 數組里的元素是一一對應的朝群,inputRange數組元素是數字,必須從小到大
我們要實現的動畫是在0到1的中間變長中符, 即0.5時應該是最大的
const scaleValue = (defaultScale) => {
? ? ? ? ? ? let number = 4
? ? ? ? ? ? let arr = new Array(number * 2)
? ? ? ? ? ? return arr.fill(0).reduce(function(pre, cur, idx){
? ? ? ? ? ? ? ? idx == 0 ? pre.inputRange.push(cur) : pre.inputRange.push(pre.inputRange[idx-1] + 0.5);
? ? ? ? ? ? ? ? idx%2 ? pre.outputRange.push(defaultScale) : pre.outputRange.push(1)
? ? ? ? ? ? ? ? return pre
? ? ? ? ? ? ? ? }, {inputRange: [], outputRange: []})
? ? ? ? }
通過reduce函數生成一個對象姜胖,最后的結果是 codepen
這樣把生成的scaleX的值傳到translate里面,即可生成動效
源碼地址:https://github.com/JunIce/react-native-scroll-customTabBar淀散, 希望大家給個star右莱, 這年頭多要點工資就看star了??????
把思路寫給大家分享一下,有什么錯誤希望能指出來档插。謝謝??