
4.1 基础视图组件
基础视图组件是指使用简单,并且不需要和其他视图组件结合就可以独立使用的一部分组件,这部分组件是组成界面的基础元素。
4.1.1 icon组件
icon是小程序组件库中提供的一个创建指定意义小图标的组件。组件库中默认定义了9种类型的图标,开发者可以根据需要进行使用,并且可以对其颜色进行自定义。
在测试工程中创建一个新的页面,命名为icon,创建页面的方法非常简单:首先,在pages文件夹下新建一个命名为icon的目录,在icon目录下右击,选择新建Page,命名为icon即可,创建完成后,开发工具会自动生成4个基础文件,并且在app.json文件中注册icon页面;其次,为了方便测试页面,可以修改开发工具的编译模式,在开发工具的工具栏上选择“添加编译模式”,如图4-1所示。

图4-1 添加编译模式
在弹出的窗口中,将模式名称命名为icon,启动页面设置为icon页面,其他无须修改,单击“确定”保存模式即可,如图4-2所示。

图4-2 自定义编译模式
之后项目将默认以icon页面作为启动页,这样可以方便观察与调试。
在icon.js文件中加载如下初始化数据:

上面的数据定义了icon的所有可用类型,每种类型对应不同样式的图标,在icon.wxml文件中编写如下代码:

上面的代码根据数据源个数循环创建了一组icon图标组件,并将其布局在界面上,icon组件的size属性设置图标的尺寸,color属性设置图标的颜色,type属性设置图标的类型,在icon.wxss文件中编写如下代码:

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

图4-3 icon组件的运行展示
4.1.2 text组件
text组件的主要作用是展示文本。在测试工程中新建一个text页面,在text.wxml文件中编写如下代码:

上述代码创建了一段简单的文本视图,效果如图4-4所示。

图4-4 text组件的运行效果
text组件中只能够嵌套text组件,通过text组件嵌套的方式可以在一段文本中设置不同风格的多段文本块。
默认文本组件只能够进行文本的显示,不可以进行交互,但可以添加selectable属性使其支持文本选中,选中文本后可以进行复制、查询等操作。
4.1.3 rich-text组件
前面提及,text组件中只能嵌套text组件,虽然可以通过text组件的style属性定制文本的展示样式,但是其功能依然有限,如无法在文本中插入图片、超链接等。小程序组件库中还提供了一个专门用来创建富文本的组件:rich-text组件。
rich-text组件允许在文本中插入常用的HTML节点,包括图片、段落、超链接等。rich-text组件的使用也非常简单,可以通过定义一组HTML节点创建富文本组件。
在测试工程中新建一个rich-text页面,在rich-text.wxml文件中编写如下代码:

上面的代码设置了rich-text组件的nodes属性,这个属性对应的数据定义在rich-text.js文件中:

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

图4-5 rich-text组件的运行效果
如上述代码所示,rich-text组件通过一组节点进行定义,节点由对象描述,节点对象可配置的属性如表4-1所示。
表4-1 节点对象可配置的属性

rich-text组件支持的HTML标签如表4-2所示。
表4-2 rich-text组件支持的HTML标签

4.1.4 progress组件
progress组件用来创建进度条视图,其使用非常简单,并且提供了丰富的可定制化的属性,示例代码如下:

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

图4-6 progress组件的运行效果
progress组件的常用属性如表4-3所示。
表4-3 progress组件的常用属性

4.1.5 button组件
button是小程序组件库提供的一个封装完善的按钮组件,其实,在小程序开发中,并非只有button组件才能作为用户交互的按钮,自定义的view组件都可以通过绑定用户交互事件的方式接收用户的操作。除提供最基础的交互功能外,button组件还封装了许多微信官方提供的服务接口,如进行用户登录、进行当前页面的分享等。
在测试工程中新建一个button页面,在button.wxml文件中编写如下代码:

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

图4-7 button组件的运行效果
button组件的size属性用来设置组件的尺寸,可选值有default和mini,default为默认尺寸的按钮组件,mini为小尺寸按钮。type属性设置按钮的风格,风格会影响按钮的渲染颜色:primary风格的按钮会被渲染为绿色,default风格的按钮会被渲染为白色,warn风格的按钮会被渲染为红色。
plain属性用来设置按钮的背景色是否透明。除了这些属性,button组件还可配置其他属性,如表4-4所示。
表4-4 button组件可配置属性列举

表4-4列举了button组件的基础属性,button组件更多是用来作为特殊微信服务的入口,如上面的实例代码,当单击页面上的按钮时会弹出分享弹窗,button组件可以通过设置open-type属性使用微信开发功能,open-type支持的功能如表4-5所示。
表4-5 open-type支持的功能

调用微信开放功能,通常需要配置button组件的属性一起使用,button组件中与微信开放功能相关的属性如表4-6所示。
表4-6 button组件中与微信开放功能相关的属性
