在小程序中,有的頁面需求可能需要我們做一個自定義的導航欄, 今天就來踩一踩坑
首先需要在app.js 中給全局的導航欄隱藏,
1 // app.js 2 3 window: { 4 navigationStyle: 'custom', 5 }, 6 // navigationStyle 接受兩個參數 ['default', 'custom']: ['系統導航欄, 默認值', '隱藏系統導航欄']
這里隱藏掉默認的導航欄之后 可以通過自定義組件的形式,DIY 一個導航欄, 值得注意的是, 當隱藏系統導航欄后, 頁面會直接頂到狀態欄上, 不同機型的狀高度可能不一致, 尤其是針對 蘋果X 的劉海屏等 水滴屏, 需要做適配,
解決方法: Taro.getSystemInfo 中 有個屬性叫做 statusBarHeight , 通過此方法即可獲取手機狀態欄的高度, 也可以在 未隱藏系統導航欄時 通過 getSystemInfo 中的 可視區域高度 screenHeight - 窗口高度 windowHeight - 狀態欄高度 statusBarHeight 的差值結果得出 系統導航欄的高度, 這里我通過僅拿蘋果手機的不同機型進行測試得出 系統導航欄高度為 44px , 便直接把 自定義導航的高度定為 44px (有興趣的可以試試)
還有知道主要一點的是 隱藏系統導航欄后 右上角膠囊狀的按鈕 還是后保留在原始位置的
1 // app.js 2 3 Taro.getSystemInfo({}) 4 .then(res => { 5 Taro.$navBarMarginTop = res.statusBarHeight || 0 6 }) 7 // 將狀態欄高度掛載全局
這里的寫法很多 可以申明在 app.js 中, 也可以放在 redux中 等等 ,
接下來自定義 導航欄 Navbar
1 // src/components/Navbar/index 2 3 import Taro from '@tarojs/taro' 4 import { View } from '@tarojs/components' 5 import './index.scss' 6 class Navbar extends Taro.Component { 7 8 render() { 9 const style = { 10 paddingTop: Taro.$navBarMarginTop + 'px' 11 } 12 // 將狀態欄的區域空余出來 13 return ( 14 <View className='navbarWrap' style={style}> 15 <View className='navbar'>自定義導航欄</View> 16 </View> 17 ); 18 } 19 } 20 export default Navbar 21 22 // 這里導航欄內容可以自行配置
然后就是在頁面中使用 自定義導航欄
頁面中使用方法有兩種, 一種是常規的import 組件, taro 中給我們提供了第二種方式
1 // index/index.js 首頁 2 3 import NavBar from '../../components/Navbar/index' 4 5 class Index extends Component { 6 config = { 7 navigationBarTitleText: '首頁', 8 usingComponents: { 9 'navbar': '../../components/Navbar/index', // 書寫第三方組件的相對路徑 10 }, 11 } 12 render () { 13 return ( 14 <View className='index'> 15 <NavBar /> 16 { /* 方法一 */ } 17 <navbar /> 18 { /* 方法一二 */ } 19 20 </View> 21 ) 22 } 23 } 24 25 export default Index
所幸的是方法二中同樣支持 懶人路徑寫法, 具體工作中可自行選擇自己喜歡的寫法 這里就不做演示,
如果在開發中遇到了 jsEnginScriptError Component is not found in path 類似的報錯,請首先確定自己路徑的是否正確引用以及大小寫是否有問題,
沒問題的話 , 重新 yarn dev:weapp 即可