鸿蒙开发中的组件复用方法
·
鸿蒙开发中的组件复用方法
在鸿蒙(HarmonyOS)应用开发中,组件复用是提高开发效率、保持UI一致性的重要手段。以下是鸿蒙开发中常用的组件复用方法:
1. 自定义组件
最基础的复用方式,将可复用的UI和逻辑封装成自定义组件。
@Component
struct MyCustomComponent {
@Prop title: string
build() {
Column() {
Text(this.title)
.fontSize(20)
// 其他公共UI元素
}
}
}
2. @Builder装饰器
用于构建可复用的UI片段,可以在多个地方调用。
@Builder function commonButton(text: string) {
Button(text)
.width(100)
.height(40)
.backgroundColor(Color.Blue)
}
// 使用
commonButton("点击我")
3. @Extend装饰器
扩展原生组件样式,实现样式复用。
@Extend(Text) function fancyText() {
.fontSize(24)
.fontColor(Color.Red)
.fontWeight(FontWeight.Bold)
}
// 使用
Text("样式化文本").fancyText()
4. 组件模板
通过<template>定义可复用的模板。
@Entry
@Component
struct TemplateExample {
@State isShow: boolean = true
build() {
Column() {
MyTemplate({ title: '标题1', isShow: this.isShow })
MyTemplate({ title: '标题2', isShow: !this.isShow })
}
}
}
@Builder function MyTemplate(title: string, isShow: boolean) {
if (isShow) {
Text(title).fontSize(20)
}
}
5. 公共样式
通过定义公共样式类实现复用。
// 定义样式类
.styles {
.width(100%)
.height(50)
.backgroundColor(Color.Gray)
}
// 使用
Text("样式文本").styles()
6. 状态管理共享组件
通过状态管理(如AppStorage)实现跨组件数据共享。
// 共享状态
AppStorage.SetOrCreate('themeColor', Color.Blue)
// 组件中使用
@Component
struct ThemedComponent {
@StorageLink('themeColor') themeColor: Color = Color.Blue
build() {
Column() {
Text("主题文本").fontColor(this.themeColor)
}
}
}
7. 动态组件加载
通过条件渲染或动态导入实现组件复用。
@Component
struct DynamicComponent {
@State currentComponent: string = 'ComponentA'
build() {
Column() {
if (this.currentComponent === 'ComponentA') {
ComponentA()
} else {
ComponentB()
}
}
}
}
8. 组件库
将常用组件打包成独立的模块/库,供多个项目复用。
选择建议
- 简单UI片段复用:使用@Builder
- 样式复用:使用@Extend或公共样式
- 复杂组件复用:创建自定义组件
- 跨组件状态共享:使用状态管理
- 大型项目:考虑组件库方式
根据具体场景选择合适的方法,可以显著提高鸿蒙应用的开发效率和可维护性。
更多推荐

所有评论(0)