本文分享一套适配 Skyline 渲染引擎的自定义导航栏组件,旨在解决多机型兼容及布局自适应问题。
核心特性
自动获取右上角胶囊按钮信息,动态计算导航高度,完美兼容不同机型。
智能布局切换:未传入 Logo 时标题屏幕居中;传入 Logo 时展示“Logo + 标题”左对齐布局。
支持自定义渐变背景及标题文字颜色,满足多样化 UI 需求。
深度适配 Skyline 渲染模式,居中方案采用 left:50% + transform,有效规避 Flex 布局潜在 Bug。
内置占位元素,防止 Fixed 定位导航遮挡页面主体内容。
标准组件化封装,父页面通过属性传参,支持短横线命名自动映射为驼峰变量。
组件代码实现
WXML 结构
components/nav-home/nav-home.wxml
<view class="nav-home-bar" style="height:{{navHeight}}px;{{bgStyle}}"><view class="capsule-line" style="top:{{menuTop}}px;height:{{menuHeight}}px;"><!-- 无logo:绝对居中,屏幕中线 --><view wx:if="{{!logoSrc}}" class="title-center"><text class="title" style="color:{{titleColor}}">{{title}}</text></view><!-- 有logo:靠左 --><view wx:else class="title-left"><image class="logo" src="{{logoSrc}}" mode="aspectFill"></image><text class="title" style="color:{{titleColor}}">{{title}}</text></view></view></view><view style="height:{{navHeight}}px;"></view>
WXSS 样式
components/nav-home/nav-home.wxss
.nav-home-bar {position: fixed;top: 0;left: 0;width: 100%;z-index: 999;}.capsule-line {position: absolute;left: 0;right: 0;height: 100%;display: flex;align-items: center;}.title-center {position: absolute;left: 50%;transform: translateX(-50%);}.title-left {display: flex;align-items: center;gap: 12rpx;padding-left: 24rpx;}.logo {width: 60rpx;height: 60rpx;border-radius: 50%;}.title {font-size: 36rpx;font-weight: 700;line-height: 1;}
JS 逻辑
components/nav-home/nav-home.js
Component({properties: {logoSrc: {type: String,value: ""},title: {type: String,value: ""},bgStyle: {type: String,value: "background:linear-gradient(to bottom, #ffeef2 0%, #fff4f6 45%, #ffffff 100%);"},titleColor: {type: String,value: "#c71a41"}},data: {navHeight: 0,menuTop: 0,menuHeight: 0},lifetimes: {attached() {setTimeout(() => {const menu = wx.getMenuButtonBoundingClientRect();console.log("胶囊信息:", menu);this.setData({navHeight: menu.bottom,menuTop: menu.top,menuHeight: menu.height});}, 100)}}})
JSON 配置
components/nav-home/nav-home.json
{"component": true}
使用说明
属性命名规范
小程序组件遵循标准属性映射规则:父页面使用短横线命名(如 logo-src),组件 properties 接收时自动转换为驼峰命名(如 logoSrc)。
页面调用示例
在 home 页面中引入并使用:
home.json
{"navigationStyle": "custom","usingComponents": {"nav-home": "/components/nav-home/nav-home"}}
home.wxml
<nav-hometitle="橙味活动页"bg-style="background:linear-gradient(to bottom, #ff7b22 0%, #ff8c38 100%);"title-color="#ffffff"></nav-home>

