React Navigation 導航欄樣式調整+底部角標訊息提示
五一佳節匆匆而過,有人選擇在外面看人山人海,有人選擇宅在家中度過五一,也有人依然堅守在第一線,致敬!
這是堅持學習 react-native
的第二篇文章,可能會遲到,但是絕不會缺席,這篇要涉及到的是 react-navigation
,也是rn社群主推的一個導航庫。
網上關於 react-navigation
的基本使用也是一抓一大把,這裡對於它的使用不做過多介紹,主要記錄使用過程中的其他問題。
因為android 和iOS 手機的不同,導航欄的顯示也不太一樣,而這篇文章會盡量的配置屬性,讓兩端的導航欄樣式、頁面跳轉的動畫保持一致,同時還會介紹底部導航欄新增角標的方法。
這裡使用的是 3.9.1版本 ,網上好多文章是2.x版本的,用法基本大同小異。
android 導航欄標題居中適配
預設情況下,iOS的標題居中顯示,而android的則不!!!
解決: createStackNavigator
的 defaultNavigationOptions
屬性裡配置 textAlign
和 flex
const AppStackNavigator = createStackNavigator({ HomeScreen: {screen: HomeScreen}, RainScreen: {screen: RainScreen} },{ defaultNavigationOptions:{ ... headerTitleStyle: { ... textAlign: "center", //用於android 機型標題居中顯示 flex:1 } } })
注:android機型標題預設不居中, textAlign
和 flex
的屬性配置用於android機型標題居中顯示。
在這種情況下,如果配置了 headerLeft
或者 headerRight
屬性,會出現標題偏移的現象。
直接在 defaultNavigationOptions
裡配置空view的 headerLeft
和 headerRight
defaultNavigationOptions:{ ... headerTitleStyle: { ... textAlign: "center", //用於android 機型標題居中顯示 flex:1, }, headerRight: <View/>, headerLeft: <View/> }
這時候標題居中,同時可以在各自的頁面裡面去重寫 headerLeft
的樣式。
android 導航欄去除陰影樣式
android的導航欄還有陰影的樣式,新增 elevation
設定陰影的偏移量
defaultNavigationOptions:{ headerStyle:{ backgroundColor:"#fff", elevation:0.5 }, ... }
至此的導航欄的效果跟iOS基本保持一致。
android 頁面跳轉動畫,自右向左開啟
預設的android頁面跳轉是自下而上開啟頁面,而要與iOS的保持一致的自右向左,配置 transitionConfig
屬性。
const AppStackNavigator = createStackNavigator({ HomeScreen: {screen: HomeScreen}, ... },{ defaultNavigationOptions:{ ... }, transitionConfig: () => ({ screenInterpolator: (sceneProps) => { return StackViewStyleInterpolator.forHorizontal(sceneProps) }, }), })
底部導航新增訊息角標
有時候我們會遇到這樣的需求,在底部導航處新增訊息的角標,提醒使用者閱讀的。
在 tabBarIcon
的屬性裡直接新增圖示顯示的,這裡的 msg
變數數值是全域性的,只做演示使用,實際專案裡可以根據介面返回資料,可以搭配mobx 一起使用。
const rootTab = createBottomTabNavigator({ ... info: { screen: InfoStack, navigationOptions: { tabBarLabel: "訊息", tabBarIcon: ({focused, tintColor}) => { let icon = focused ? require('../resources/img/mine_icon_message_selected.png') : require('../resources/img/mine_icon_message_default.png'); return <View> { msg > 0 ? <View style={{ width:12, height:12, justifyContent:"center", position: 'absolute', zIndex: 9, backgroundColor: "#FB3768", borderRadius:6, right:0, top:-2, }}> <Text style={[{fontSize:10, color:"#fff", textAlign:"center",}]}>{msg}</Text> </View> : null } <Image source={icon} style={{width: 34, height: 26}}/> </View> } } } },{ ... defaultNavigationOptions: ({navigation, screenProps}) => ({ tabBarOnPress: (obj) => { //點選的時候清除訊息 const {routeName} = obj.navigation.state; if (routeName === "info") { msg = 0 } obj.navigation.navigate(obj.navigation.state.key) } }) })
以上幾點是在 react-navigation
的使用過程中遇到的問題以及解決方法,相關程式碼已經傳到了github上 https://github.com/taixiang/reactNativeDemo ,僅供參考,如果有更好的方式 歡迎一起學習研究。
歡迎關注我的個人部落格: https://www.manjiexiang.cn/
更多精彩歡迎關注微訊號:春風十里不如認識你
一起學習,一起進步,歡迎上車,有問題隨時聯絡,一起解決!!!