背景
小程序默认的头部可以选择背景,title 文字和颜色(颜色只支持黑白)。如果这样满足不了我们的需求,我们就需要用自定义头了。
当然,我们尽量使用默认的自定义头部,比如,这个设计背景是一个渐变的,那么我可以跟设计商量,头部用一个纯色,到内容部分使用渐变,这样我们就没用必要重新去做一个自定义头了。
因为使用自定义头需要计算在不同手机上的高度,所以今天我封装了一个自定义头。
自定义header组件
<view class="custom-header" style="height: {{ navBarHeight }}px;background-color: {{ backgroundColor }};color: {{ titleColor }};">
<view class="header-left">
<icon name="bc-home" wx:if="{{ leftIconType === 'home' }}" bind:tap="goHome" />
<icon name="bc-fenxiang" wx:if="{{ leftIconType === 'back' }}" bind:tap="goBack" />
</view>
<view class="header-center">
<view class="center-title">{{ title }}</view>
</view>
<view class="header-right"></view>
</view>
<view
class="page"
style="top: {{ navBarHeight }}px;"
>
<slot></slot>
</view>
const navBarHeight = wx.getSystemInfoSync().statusBarHeight + 44;
Page({
/**
* 组件的属性列表
*/
props: {
title: {
type: String,
value: '标题',
},
backgroundColor: {
type: String,
value: '#f7f7f7',
},
titleColor: {
type: String,
value: '#000',
},
leftIconType: {
type: String,
value: 'back',
},
},
/**
* 组件的初始数据
*/
data: {
navBarHeight: navBarHeight,
},
/**
* 组件的方法列表
*/
methods: {
goHome () {
this.triggerEvent('goHome');
},
goBack () {
this.triggerEvent('goBack');
},
},
});
.custom-header {
position: fixed;
left: 0;
right: 0;
top: 0;
z-index: 10;
display: flex;
align-items: center;
.header-left {
position: absolute;
left: 16px;
bottom: 22px;
transform: translateY(50%);
height: 32px;
display: flex;
align-items: center;
cursor: pointer;
.left-image {
width: 20px;
height: 20px;
}
}
.header-center {
position: absolute;
bottom: 22px;
left: 104px;
right: 104px;
transform: translateY(50%);
font-size: 14px;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.page {
position: fixed;
left: 0;
right: 0;
bottom: 0;
overflow-y: scroll;
}
基础用法
<custom-header title="{{ title }}" bind:goBack="goBack" />
API
Props
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
title | 标题 | String | 标题 |
backgroundColor | 背景颜色 | String | #f7f7f7 |
titleColor | 标题字体颜色 | String | #000000 |
leftIconType | 左icon类型支持 (home,back) | String | back |
Events
事件名 | 说明 | 参数 |
---|---|---|
bind:goHome | 左边link点击事件 | event |
bind:goBack | 左边link点击事件 | event |