1. 程式人生 > >Taro 小程式 自定義導航欄

Taro 小程式 自定義導航欄

在小程式中,有的頁面需求可能需要我們做一個自定義的導航欄, 今天就來踩一踩坑

首先需要在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  即可

&n