> 技术文档 > 鸿蒙仓颉开发语言实战教程:自定义组件_仓颉组件编程

鸿蒙仓颉开发语言实战教程:自定义组件_仓颉组件编程

关于仓颉开发语言我们已经连续分享了很多天,相信大家对于仓颉开发语言已经有了一定的了解。今天我们继续进阶,分享一个仓颉开发语言中的自定义组件知识。

本文案例就以上一篇文章中的自定义tabbar为例,因为我们自己开发的tabbar一直放在index.cj文件中总是不太好的,还是要把它拿出来封装一下。

为了较大型项目的文件管理,我在cangjie文件夹下创建了components文件夹,然后在这里创建组件文件,我创建的是yltabbar.cj.

创建文件之后,可以看到依然是初始化了一行代码,我们还是把四大引用拿过来,然后添加build方法,注意自定义组件就不需要@Entry来修饰了,只用@Component:

internal import ohos.base.*internal import ohos.component.*internal import ohos.state_manage.*import ohos.state_macro_manage.*@Componentpublic class yltababar { func build() { }}

然后把tabbar的内容复制到build方法下。

现在如果我们想要给自定义组件传递一些参数,比如tabbar的元素列表,你就可以这样写:

var tabList: Array

这是一个父子单向传递的参数,只能由父组件传递给自组件。我们还有一个参数currenttabIndex,用来记录当前选择的元素序号,这个参数在父组件中也需要用到,这时候就需要使用@Link修饰符:

@Link var currenttabIndex:Int64

现在就可以在页面中使用组件并传递参数了:

yltababar(tabList:this.tabList,currenttabIndex:this.currenttabIndex)

最后跟大家分享封装组件的完整代码:

package ohos_app_cangjie_entry.componentsinternal import ohos.base.*internal import ohos.component.*internal import ohos.state_manage.*import ohos.state_macro_manage.*import cj_res_entry.appimport ohos_app_cangjie_entry.model.TabItemimport std.os.posix.linkimport std.console.Console@Componentpublic class yltababar { var tabList: Array @Link var currenttabIndex:Int64 var controller: TabsController = TabsController() func build() { Row { ForEach(this.tabList, itemGeneratorFunc: {item: TabItem, index: Int64 => Column { if(this.currenttabIndex == index){  Image(item.selectIcon).width(28).height(28)  Text(item.title).fontSize(15).fontColor(0xd84642).margin(top: 3) }else {  Image(item.icon).width(28).height(28)  Text(item.title).fontSize(15).fontColor(Color.GRAY).margin(top: 3)  } } .onClick({evet => this.currenttabIndex = index;this.controller.changeIndex(Int32(this.currenttabIndex))}) }) } .width(100.percent) .height(60) .alignItems(VerticalAlign.Center) .justifyContent(FlexAlign.SpaceAround) }}

 #HarmonyOS语言##仓颉##购物#