1. 官方文档指南
-
TabContent的使用: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-container-tabcontent-V5
-
@Builder装饰器的使用:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-builder-V5
2. @Builder装饰器:自定义构建函数的使用
-
有何作用
开发者可以将重复使用的UI元素抽象成一个方法,在build方法里调用
-
定义的语法:
@Builder MyBuilderFunction() { ... }
使用方法:
this.MyBuilderFunction()
- 允许在自定义组件内定义一个或多个@Builder方法,该方法被认为是该组件的私有、特殊类型的成员函数。
- 自定义构建函数可以在所属组件的build方法和其他自定义构建函数中调用,但不允许在组件外调用。
- 在自定义函数体中,this指代当前所属组件,组件的状态变量可以在自定义构建函数内访问。建议通过this访问自定
- 义组件的状态变量而不是参数传递。
3.支持全局自定义构建函数
定义的语法:
@Builder function MyGlobalBuilderFunction() { ... }
使用方法:
MyGlobalBuilderFunction()
如果不涉及组件状态变化,建议使用全局的自定义构建方法。
@Builder装饰器可以传递参数
3. 自定义组件内自定义构建函数
@Builder
tabBuilder(index: number,title:string,icon:Resource) {
Column() {
Image(icon)
.width(24)
.height(24)
.fillColor(this.currentIndex==index? this.selectedFontColor : this.fontColor)
.margin({ bottom: 4 })
.objectFit(ImageFit.Contain)
Text(title)
.fontSize(10)
.fontColor(this.currentIndex==index? this.selectedFontColor: this.fontColor)
.fontWeight(500)
.lineHeight(14)
}
}
4. 代码实现全过程
@Entry
@Component
struct Index {
//默认颜色
@State fontColor: string = '#666666'
//选中时的颜色
@State selectedFontColor: string = '#00c800'
//默认下标
@State currentIndex: number = 0
@Builder
tabBuilder(index: number,title:string,icon:Resource) {
Column() {
Image(icon)
.width(24)
.height(24)
.fillColor(this.currentIndex==index? this.selectedFontColor : this.fontColor)
.margin({ bottom: 4 })
.objectFit(ImageFit.Contain)
Text(title)
.fontSize(10)
.fontColor(this.currentIndex==index? this.selectedFontColor: this.fontColor)
.fontWeight(500)
.lineHeight(14)
}
}
build() {
Column() {
Tabs({ barPosition: BarPosition.End }) {
TabContent() {
Text('微信好友列表').fontSize(30)
}
.tabBar(this.tabBuilder(0,'微信',$r('app.media.img_home')))
TabContent() {
Text('通讯录').fontSize(30)
}
.tabBar(this.tabBuilder(1,'通讯录',$r('app.media.img_address')))
TabContent() {
Text('发现').fontSize(30)
}
.tabBar(this.tabBuilder(2,'发现',$r('app.media.img_find')))
TabContent() {
Text('我的').fontSize(30)
}
.tabBar(this.tabBuilder(3,'我的',$r('app.media.img_mine')))
}
//设置不允许左右滑动
.scrollable(false)
//设置点击事件
.onChange((index: number) => {
this.currentIndex = index
})
}
}
}
强烈建议:图片建议使用svg格式的,因为选中和不选中是两种颜色,可以直接使用Image.fillColor给图片设置颜色,一张图片就够了,如果是.png格式的,就需要两张
Image的objectFit属性用来设置图片的填充效果
官方文档指南:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-image-V5#objectfit