
4.3 选择器组件
小程序组件库中提供了适合各种场景使用的选择器组件,如时间选择、日期选择、城市选择等,开发者也可以根据实际需求为选择器提供自定义的数据源。
4.3.1 普通选择器
普通选择器用来展示开发者提供的一组简单选项,以性别选择为例,在测试工程中创建一个新的页面,命名为picker,在picker.wxml文件中编写如下代码:

picker就是小程序中的选择器组件,通过mode属性设置不同的模式,其中,selector为普通选择器模式,选择器的属性通过range属性设置,在picker.js文件的data对象中添加如下属性:

实现绑定的change()函数如下:

运行上述代码,当单击页面上的文本时,会弹出选择列表。运行代码,效果如图4-15所示。

图4-15 普通选择器的运行效果
从图4-15可以看到,选择器中选项的值就是range属性指定的数组中字符串的值,如果数组中存放的不是普通字符串,而是对象,也可以指定选择器选择对象的某个属性作为选项进行显示。例如,修改data数据的示例代码如下:

修改picker.wxml文件,示例代码如下:

运行代码,效果如图4-16所示。

图4-16 用对象属性作为选项的值
普通模式的选择器组件的常用属性如表4-13所示。
表4-13 普通模式的选择器组件的常用属性

4.3.2 多列选择器
普通选择器只支持单列数据选择,但很多时候需要为用户提供多列选择项目。例如,省份城市选择器,第1列需要用户选择省份,第2列需要用户选择当前省份下的城市。picker组件也提供了多列模式,设置mode属性为multiSelector即可。
在picker.js文件中添加一组省市数据和一个数组标记默认选择的省市,示例代码如下:

多列选择器使用二维数组的方式组织数据,其中,每个数组定义选择器中每列的所有选项,currentCity用来标记每列的选中位置。在picker.wxml文件中添加组件标签,示例代码如下:

运行代码,效果如图4-17所示。

图4-17 多列选择器的运行效果
多列模式下的选择器组件的常用属性如表4-14所示。
表4-14 多列模式下的选择器组件的常用属性

4.3.3 时间选择器
时间选择器专门为用户提供进行时间的选择,其需要设置picker组件的mode属性为time,示例代码如下:

运行代码,效果如图4-18所示。

图4-18 时间选择器的运行效果
时间模式下的选择器组件的常用属性如表4-15所示。
表4-15 时间模式下的选择器组件的常用属性

4.3.4 日期选择器
日期选择器与时间选择器的用法基本一致,为用户提供年、月、日的选择,设置picker组件的mode属性为date即可,示例代码如下:

运行代码,效果如图4-19所示。

图4-19 日期选择器的运行效果
日期选择器的常用属性如表4-16所示。
表4-16 日期选择器的常用属性

4.3.5 地区选择器
前面已经介绍了多种场景下使用的选择器组件,通过多列选择器可以根据需要定制各种复杂的选择器组件。起始,对于地区选择,小程序也提供了专门的选择器供开发者直接使用,将mode属性设置为region即可,示例代码如下:

运行代码,效果如图4-20所示。

图4-20 地区选择器的运行效果
地区选择器的常用属性如表4-17所示。
表4-17 地区选择器的常用属性

4.3.6 选择器视图
通过上面的介绍可知,picker组件是系统封装好的一个弹窗组件。小程序组件库中也提供了直接定制选择器视图的组件:picker-view。
picker-view是一个直接显示在页面上的选择器视图,其内只能嵌套picker-view-column组件,picker-view-column用来描述选择器视图中的一列,其内可以放置其他任意组件,也可以使用循环的方式放入一组子组件。示例代码如下:

运行代码,效果如图4-21所示。

图4-21 自定义选择器视图的运行效果
picker-view组件的常用属性如表4-18所示。
表4-18 picker-view组件的常用属性
