微信小程序——自定义导航栏

1,851 阅读2分钟

背景

微信小程序默认提供了一个标准的导航栏,但有些时候我们需要自定义导航栏来中集成搜索框、自定义背景图、返回首页按钮等功能,来满足业务需求。

基本配置

首先在app.json(page.json)中配置navigationStyle,支持两个值:

  1. default 默认样式
  2. custom 自定义导航栏,只保留右上角胶囊按钮。
// 全局配置app.json
{
    "window":{
        "navigationStyle": "custom", // 由default改为custom 
    }
}

// 单页面配置page.json
{
    "navigationStyle": "custom",
}

注:页面中配置项在当前页面会覆盖 app.json 中相同的配置项

组件封装

components/nav-bar/

nav-bar.wxml

// components/nav-bar/nav-bar.wxml
<view style="height:{{navigationHei}}px; top:{{navigationTop}}px; padding-left:{{paddingLeft}}px" class="nav-bar">
  <view class="nav-bar-left">
    <view class="left">
      <slot name="left"> </slot>
    </view>
    <view class="default_left"> 
      <text>我是默认left</text>
    </view>
  </view> 
  <view class="nav-bar-content">{{title}}</view>
</view>

nav-bar.js

要点:

  1. 使用wx.getSystemInfoSync()获取设备基础信息,

  2. 使用wx.getMenuButtonBoundingClientRect()获取右上角胶囊的信息

  3. 导航栏高度公式:导航栏高度 = 状态栏到胶囊的间距(胶囊距上边界距离-状态栏高度) * 2 + 胶囊高度。

注:状态栏到胶囊的间距 = 胶囊到下边界距离。所以这里需要*2

// components/nav-bar/nav-bar.js
Component({
  options: {
    multipleSlots: true  // 重要,启用组件定义时的多 slot 支持
  },
  properties: {
    title: {
      type: String,
      value: '默认标题'  // 默认标题文本
    },
  },
  data: {
    navigationTop: 0,  // 导航栏顶部高度
    navigationHei: 20,  // 导航栏高度,默认值为 20
    paddingLeft: 0,  // 导航栏左侧内边距,默认值为 0
  },
  ready: function () {
    // 获取系统信息
    const { screenWidth, statusBarHeight } = wx.getSystemInfoSync();

    // 获取胶囊按钮信息
    const { height, top, right } = wx.getMenuButtonBoundingClientRect();

    // 计算左侧内边距
    const paddingLeft = screenWidth - right;

    // 计算导航栏高度
    const navigationHei = (top - statusBarHeight) * 2 + height;

    // 更新数据
    this.setData({
      navigationTop: statusBarHeight,
      navigationHei,
      paddingLeft
    });
  },
})

nav-bar.wxss

// components/nav-bar/nav-bar.wxss
.nav-bar{
  position: fixed;
  width:100vw;
  left:0;
  top:0;
  background: orange;
  box-sizing: border-box;
}
.nav-bar-left{
  display: flex;
  height: 100%;
  align-items: center;
}

.nav-bar-content{
  position: absolute;
  left:0;
  top:0;
  width:100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}


.left:empty + .default_left {
  display: flex;
}
.default_left {
  display: none;
  align-items: center;
  font-size: 28rpx;
}

nav-bar.json

// components/nav-bar/nav-bar.json
{
  "usingComponents": {},
  "navigationStyle":"custom",
  "navigationBarTextStyle":"black"
}

实践应用

页面配置引入该自定义组件

// app.json 
{ 
     "usingComponents": { 
         "nav-bar": "/components/nav-bar/nav-bar",
     } 
 }

在页面的WXML文件中使用

// xxx.wxml
<view class="page">
    <nav-bar title="传标题咯" />
</view>

image.png

最后

具体的业务和样式还需要根据自身产品来设定,除了上面基础的自定义导航栏,我们还可以对导航栏进行特殊的定制,比如在导航栏放置搜索框,日期选择,时间,日期和天气信息等。