目录
前言
在ArkUI中,自定义组件的生命周期管理是开发高效应用的关键。
以下是自定义组件生命周期的详细说明。
1.自定义组件的基本用法
下面的代码中展示了一个最基础的自定义组件:
@Component
struct CommonButton {
build() {
Button('自定义组件生命周期', { type: ButtonType.Capsule }).margin({top:20})
}
}
调用的代码如下:
@Component
struct CommonButton {
build() {
Button('自定义组件生命周期', { type: ButtonType.Capsule }).margin({top:20})
}
}
@Entry
@Component
struct ComponentPage {
private someColor: Color = Color.Pink;
build() {
Column() {
CommonButton().onClick(()=>{
console.log("自定义这")
})
}
.height('100%')
.width('100%')
.backgroundColor('#F5F5F5')
}
}
图1.最简单的自定义组件
这里自定义组件和页面是写在一个文件中的,如果想做成一个组件,让其它页面也能调用。我们可以新创建一个文件,然后使用export关键字导出组件,然后在使用的页面使用import导入即可使用。
还是以上上面的代码为例,我们新创建一个CommonButton文件:
@Component
export struct CommonButton {
build() {
Button('自定义组件生命周期', { type: ButtonType.Capsule }).margin({top:20})
}
}
在页面中的使用方式如下:
import { CommonButton } from './CommonButton';
@Entry
@Component
struct ComponentPage {
private someColor: Color = Color.Pink;
build() {
Column() {
CommonButton().onClick(()=>{
console.log("自定义这")
})
}
.height('100%')
.width('100%')
.backgroundColor('#F5F5F5')
}
}
2.自定义组件的基本结构
ArkUI中,自定义组件的语法如下:
struct XXX {
}
自定义组件生命周期,即用@Component或@ComponentV2装饰的自定义组件的生命周期,提供以下生命周期接口:
1.@Component
@Component装饰器仅能装饰struct关键字声明的数据结构。struct被@Component装饰后具备组件化的能力,需要实现build方法描述UI,一个struct只能被一个@Component装饰。@Component可以接受一个可选的boolean类型参数。
通过合理使用组件冻结机制,可以显著提升鸿蒙应用的渲染性能,特别是在复杂UI和长列表场景下。关键是要在动态性和性能之间找到平衡点。