關於React-Native底部tab高度初探

寫這篇文章的原因,就是產品經理希望在app下方的tab上懸浮一條提示,我們的app用的是RN的框架,於是我調研了一番如何去計算底部tab欄的高度。去RN的社區逛了一圈,發現目前沒有官方的方法能夠直接調用得到底部tab高度,甚至還看到有人因爲這一點而不滿RN的開發人員,在社區吐槽(Trash Talk)。Anyway,那我們就自己來。

一、Tab欄自身的高度

這個地方去看了源碼,發現tab的高度其實只有兩個預設值,就是針對 iphpne || ipad做了判斷,直接上相關源碼。

const tabBarStyle = [
    styles.tabBar,
    this._shouldUseHorizontalLabels() && !Platform.isPad
      ? styles.tabBarCompact
      : styles.tabBarRegular,
    style,
];

const DEFAULT_HEIGHT = 49;
const COMPACT_HEIGHT = 29;

// 樣式表
  iconWithExplicitHeight: {
    height: Platform.isPad ? DEFAULT_HEIGHT : COMPACT_HEIGHT,
  },

源碼地址:https://github.com/react-navigation/tabs/blob/d2aa789109ed0df61c0c0ac7b759ac386a720804/src/views/BottomTabBar.js

二、關於IphoneX系列的SafeArea

iphone的底部會自增一個安全區域,那麼安全區域的高度是多少呢,繼續看源碼。

LandScape Mode // 橫屏模式
paddingLeft: 44
paddingRight: 44
paddingBottom: 24
paddingTop: 0

Portrait Mode // 豎屏模式
paddingLeft: 0
paddingRight: 0
paddingBottom:34
paddingTop:44  // ... Including Status bar height

可以看到底部的安全區域只對橫豎屏做了處理,但是親測,對iphoneX系列不同deviceHeight的機型,安全區域不一樣。對於iPhonex/iPhoneXS,paddingBottom: 34,但是對於iPhoneXR/XS MAX,paddingBottom: 24,即iphonexr/xs max豎屏模式下被判斷成橫屏了。

三、總結

所以,對於安卓,你只需要得到tab的高度,然後絕對定位,不需要做特殊處理。對於iphone,你需要區別 iphoneX系列。

const styles = StyleSheet.create({
        bottomView : {
        position : "absolute",
        bottom : isIphoneXOrXS() ? dp(tab高度 + 34) : ( isIphoneXROrXSMax() ? dp(tab高度 + 24) : dp(tab高度) ), 
    },
})

插句題外話,tab高度的獲取,我是直接用模擬器的toggle inspetor得到的。

四、補充對iphoneX系列手機的css判斷方法

// iPhone X、iPhone XS
var isIPhoneX = /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 3 && window.screen.width === 375 && window.screen.height === 812;
// iPhone XS Max
var isIPhoneXSMax = /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 3 && window.screen.width === 414 && window.screen.height === 896;
// iPhone XR
var isIPhoneXR = /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 2 && window.screen.width === 414 && window.screen.height === 896;

五、小彩蛋

來看看社區裏是怎麼說的吧。 brentvatne是該框架的維護者之一。

以及社區裏有人寫了組件去判斷tabbar的高度,對於博主的項目沒有什麼幫助,但是可能會對大家有用,需要的話可以鏈接裏自取。https://github.com/react-navigation/tabs/issues/97

到這裏,完結。撒花~

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章