1.创建自定义组件
a.创建list-box组件

b.在自定义组件的list-box.json 文件中设置 "component":true

c.在自定义组件的list-box.wxml 文件中编写组件代码

d.在自定义组件的list-box.js 文件中,需要使用 Component() 来注册组件,并提供组件的属性定义、内部数据和自定义方法。

2.使用自定义组件
a.在使用自定义组件的json文件中进行引用声明

b.在使用自定义组件的js文件中定义节点属性值

c.在页面的 wxml 中就可以像使用基础组件一样使用自定义组件。节点名即自定义组件的标签名,节点属性即传递给组件的属性值。

3.效果

4.细节注意事项
一些需要注意的细节:
因为 WXML 节点标签名只能是小写字母、中划线和下划线的组合,所以自定义组件的标签名也只能包含这些字符。
自定义组件也是可以引用自定义组件的,引用方法类似于页面引用自定义组件的方式(使用 usingComponents 字段)。
自定义组件和页面所在项目根目录名不能以“wx-”为前缀,否则会报错。
注意,是否在页面文件中使用 usingComponents 会使得页面的 this 对象的原型稍有差异,包括:
使用 usingComponents 页面的原型与不使用时不一致,即 Object.getPrototypeOf(this) 结果不同。
使用 usingComponents 时会多一些方法,如 selectComponent 。
出于性能考虑,使用 usingComponents 时, setData 内容不会被直接深复制,即 this.setData({ field: obj }) 后 this.data.field === obj 。(深复制会在这个值被组件间传递时发生。)
如果页面比较复杂,新增或删除 usingComponents 定义段时建议重新测试一下。
参考:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/
网友评论