小程序组件使用
组件是小程序搭建界面的砖块。这篇分两部分:先把内置组件按用途过一遍(含容易踩的坑),再讲自定义组件的完整机制。内置组件不需要引入,写上标签就能用;自定义组件是业务复用的关键。
一、内置组件全景
微信内置组件分八大类,常用的就那二十来个,按用途记比按字母表记高效。
1.1 视图容器
| 组件 | 用途 | 关键点 |
|---|---|---|
| view | 基础容器 | 默认 block 级,相当于 div |
| scroll-view | 可滚动区域 | 必须给固定高度;横向滚动加 scroll-x |
| swiper | 轮播图 | 配合 swiper-item;indicator-dots 开指示点 |
| movable-view | 可拖拽元素 | 需放在 movable-area 内,inertia 关掉更可控 |
| cover-view | 覆盖在原生组件上的视图 | 嵌在 video/map/canvas 里用 |
| page-meta | 动态修改页面配置 | 运行时改导航栏标题/背景色 |
轮播组件的标准写法:
<swiper indicator-dots autoplay interval="4000" duration="500" circular bindchange="onSwiperChange">
<swiper-item wx:for="{{banners}}" wx:key="id">
<image src="{{item.image}}" mode="aspectFill" class="banner-img" />
</swiper-item>
</swiper>circular 不加的话,轮播到最后一张会倒着滚回去,视觉上很掉价。
scroll-view 有两个经典坑:不设高度不滚动(给 scroll-view 本身或父容器定高);下拉刷新别和 scroll-view 抢手势——用 refresher-enabled 做自定义下拉,或直接用页面的 enablePullDownRefresh。
1.2 基础内容
icon(类型/大小/颜色)、text(可选中的文本,selectable)、rich-text(富文本,nodes 传 HTML 字符串或节点数组)、progress。
rich-text 的注意事项:节点数组里的 name 会被限制(不能注入 script 等危险标签);图片必须配置域名白名单;样式要通过 user-select 控制可选性。后台返回的富文本内容建议在服务端做白名单过滤,小程序端只负责渲染。
progress 的 stroke-width 默认 6,activeColor 支持渐变色字符串:
<progress percent="{{60}}" stroke-width="12" activeColor="#07C160" backgroundColor="#e5e5e5" active />1.3 表单组件
这是交互最密集的一类,重点掌握:
| 组件 | 要点 |
|---|---|
| button | open-type 是灵魂:getUserInfo/getPhoneNumber/launchApp/openSetting/share/contact 等 |
| input | type 决定键盘;confirm-type 改键盘确认键文案;受控模式用 value + bindinput |
| textarea | auto-height 自适应高度;show-confirm-bar 控制字数条 |
| picker | 五种 mode:selector/multiSelector/time/date/region |
| picker-view | 嵌入页内的滚动选择器(省市区联动常用) |
| checkbox / radio | 组内共享一个 value 数组/字符串,用 wx:for 渲染 |
| switch / slider / stepper | 状态与数值输入 |
input 的坑最多:受控模式下每次 bindinput 都 setData 会丢光标或输入法候选错乱,正确做法是维护 value 但避免中间态频繁同步;cursor-spacing 解决键盘弹起遮挡输入框的问题;密码框用 password 属性。
<input
value="{{keyword}}"
placeholder="搜索商品"
confirm-type="search"
focus="{{inputFocus}}"
cursor-spacing="20"
bindinput="onKeywordInput"
bindconfirm="onSearchConfirm"
/>1.4 导航与页面级组件
navigator:页面跳转,open-type支持 switchTab/reLaunch/redirectTo/navigateBack,target="miniProgram"可跳其他小程序functional-page-navigator:跳微信功能页(支付、发票、车牌号等)navigation-bar:自定义导航栏(页面级配置navigationStyle: custom后使用,要处理状态栏高度)
1.5 媒体组件
image(mode 控制裁剪:aspectFill 最常用、lazy-load 懒加载)、video(object-fit、弹幕、danmu-list、全屏)、camera(需 scope.camera 授权)、live-player/live-pusher(直播,需要类目资质)、channel-video(视频号视频)。
image 的 mode 是高频错误来源:scaleToFill(默认,会变形)、aspectFit(完整显示,留白)、aspectFill(填满,裁切)、widthFix(宽度不变高度自适应,列表里保持比例用它)、heightFix。
1.6 地图与画布
map(markers/polyline/polygons/circles、show-location、subkey 个性化样式)、canvas(2d 模式用 type="2d",比旧接口性能好得多,图表库优先适配 2d)。
canvas 2d 的坑:canvas-id 在新版用 id 替代;要通过 SelectorQuery 拿 node 再取 context;离屏渲染用 wx.createSelectorQuery + NodesRef.node()。
1.7 开放能力组件
web-view(承载 H5,需业务域名配置)、open-data(展示微信用户信息,已废弃,改用头像昵称填写能力)、editor(富文本编辑器)、keyboard-accessory(输入法键盘上方工具栏)、page-container(半屏弹层,新版替代自定义弹窗做分享面板)、share-element(共享元素动画)。
1.8 新版本值得关注的组件
grid-view / list-view(Skyline 渲染引擎下的高性能列表,type="skyline" 时可用)、snapshot(页面截图)、double-tap-gesture-handler(手势)。这些依赖 Skyline 引擎,需要基础库 3.x+ 且开启实验,老项目升级前先确认兼容策略。
二、自定义组件机制
2.1 组件定义与使用
组件用 Component() 构造器定义,结构上同样是四件套。在页面的 json 里声明后使用:
{
"usingComponents": {
"star-rating": "/components/star-rating/index"
}
}<star-rating value="{{score}}" max="5" bind:change="onScoreChange" />2.2 properties 详解
properties 定义对外接口,支持类型校验和默认值:
Component({
properties: {
// 简写:只写类型
title: String,
// 完整写法:类型 + 默认值 + 监听
value: {
type: Number,
value: 0,
observer(newVal, oldVal) {
// 属性变化时触发(首次赋值也会触发)
}
},
// 对象/数组类型的默认值必须用函数返回
items: {
type: Array,
value: () => []
}
}
})对象和数组的默认值必须写成函数,写成字面量会在多个组件实例间共享同一个引用,出现改一个组件影响一片的灵异 bug。
2.3 observers:数据派生
observer 是单字段监听,observers 支持多字段组合监听,是做派生状态的正确位置:
Component({
observers: {
'width, height'(width, height) {
this.setData({ area: width * height });
},
'list.**'(list) {
// 深度监听数组内所有字段变化
}
}
})2.4 组件通信
| 方向 | 方式 | 说明 |
|---|---|---|
| 父 → 子 | properties | 数据流主通道 |
| 子 → 父 | triggerEvent | this.triggerEvent('reply', { content }) |
| 父 → 子(命令式) | this.selectComponent | 拿组件实例调方法,适合表单校验 |
| 跨层级 | relations / 全局状态 | 少用;优先考虑把状态下移到公共父节点 |
triggerEvent 的三个选项:bubbles(是否冒泡)、composed(是否穿越组件边界)、capture(捕获阶段触发)。默认情况下自定义事件需要在父组件用 bind:eventname 监听——注意是 bind: 前缀,漏掉冒号是最常见的低级错误。
2.5 behaviors:逻辑复用
behavior 是类似 mixin 的机制,可以包含 properties、data、methods、生命周期:
// behaviors/loading.js
module.exports = Behavior({
data: { loading: false },
methods: {
async withLoading(fn) {
this.setData({ loading: true });
try { return await fn(); }
finally { this.setData({ loading: false }); }
}
}
});Component({
behaviors: [require('../../behaviors/loading')],
// ...
});同名字段冲突优先级:组件覆盖 behavior,后面的 behavior 覆盖前面的。生命周期函数会合并执行,behavior 的先跑。
2.6 组件生命周期
| 阶段 | 函数 |
|---|---|
| 创建 | created(不能 setData)、attached(可 setData,节点已挂载) |
| 更新 | ready(布局完成,可操作节点) |
| 销毁 | detached |
created 里访问不到节点信息;attached 里可以拿到 this.data 初始值;ready 适合做 SelectorQuery 测量尺寸。
三、实战模式
受控表单组件:父组件持有全部表单数据,输入框组件只负责渲染和回传。好处是提交时父层直接拿全量数据,校验逻辑集中。
// 表单容器
data: { form: { name: '', phone: '' } },
onFieldChange(e) {
const { field, value } = e.detail;
this.setData({ [`form.${field}`]: value });
}// 输入框组件内部
methods: {
onInput(e) {
this.triggerEvent('change', { field: this.properties.field, value: e.detail.value });
}
}列表项组件:列表项只接收数据和 index,通过 triggerEvent 回传操作意图,永远不要在列表项内部直接改共享数据——那会让 diff 失效、状态错乱。
弹窗/动作面板:优先用 page-container 或官方 wx.showActionSheet,自己造轮子要处理好遮罩点击关闭、Esc 关闭(无障碍)、滚动穿透三个老问题。
