鸿蒙next开发-struct如何封装共用模块

在鸿蒙应用开发(基于ArkTS)中,使用 struct 封装共用模块主要涉及可复用UI组件逻辑模块化两种场景。以下是详细解决方案:


一、UI组件封装(使用 struct

通过 @Component 装饰器创建可复用的UI组件,适用于按钮、卡片等可视化元素。

示例:封装通用按钮组件
go 复制代码
// components/CommonButton.ets
@Component
export struct CommonButton {
private btnText: string = '默认按钮'
private onTap: () =>void = () => {}

  build() {
    Button(this.btnText)
      .width(120)
      .height(40)
      .backgroundColor(Color.Blue)
      .onClick(() => {
        this.onTap()
      })
  }

// 设置按钮文字
public setText(value: string): CommonButton {
    this.btnText = value
    returnthis
  }

// 设置点击事件
public setOnClick(action: () =>void): CommonButton {
    this.onTap = action
    returnthis
  }
}
调用方式
go 复制代码
// 使用组件
import { CommonButton } from'../components/CommonButton'

@Entry
@Component
struct HomePage {
  build() {
    Column() {
      CommonButton()
        .setText('立即登录')
        .setOnClick(() => {
          console.log('按钮被点击')
        })
    }
  }
}

二、逻辑模块封装(非UI)

对于工具类、服务层等非UI逻辑,使用 ES模块化 进行封装。

示例:网络请求工具类
go 复制代码
// utils/http.ets
import { HttpRequestOptions, HttpResponse } from'@ohos.net.http'

exportclass HttpUtil {
staticasyncget(url: string): Promise<HttpResponse> {
    let http = http.createHttp()
    returnawait http.request(url, {
      method: http.RequestMethod.GET
    })
  }

staticasync post(url: string, data: object): Promise<HttpResponse> {
    let http = http.createHttp()
    returnawait http.request(url, {
      method: http.RequestMethod.POST,
      header: { 'Content-Type': 'application/json' },
      extraData: JSON.stringify(data)
    })
  }
}
调用方式
go 复制代码
import { HttpUtil } from '../utils/http'

async fetchData() {
  try {
    let response = await HttpUtil.get('https://api.example.com/data')
    console.log('响应数据:', response.result)
  } catch (error) {
    console.error('请求失败:', error)
  }
}

三、进阶技巧

1. 状态共享

使用 AppStorage 实现全局状态管理:

go 复制代码
// stores/userStore.ets
import { AppStorage } from'@ohos.application'

AppStorage.SetOrCreate<string>('username', 'Guest')

exportfunction getUserName(): string {
return AppStorage.Get<string>('username')
}

exportfunction setUserName(name: string): void {
  AppStorage.Set<string>('username', name)
}
2. 组件插槽

通过 @BuilderParam 实现插槽功能:

go 复制代码
@Component
struct CardContainer {
@BuilderParam content: () =>void

  build() {
    Column() {
      this.content()
    }
    .padding(20)
    .backgroundColor(Color.White)
    .borderRadius(8)
  }
}

// 使用
CardContainer({
  content: () => {
    Text('自定义内容').fontSize(16)
  }
})

四、项目结构建议

go 复制代码
src/
├── components/      // 公共组件
├── utils/           // 工具类
├── services/        // 业务服务
├── models/          // 数据模型
├── resources/       // 静态资源
└── pages/           // 页面目录

关键点总结

  1. UI组件 :使用 @Component + struct 封装带视图的模块

  2. 逻辑模块:通过类/函数 + ES Module 导出

  3. 状态管理 :结合 AppStorage 或自有状态管理方案

  4. 类型安全:推荐使用TypeScript增强代码健壮性

根据实际场景选择封装方式,平衡复用性与灵活性。对于高频使用的功能模块,建议通过抽象接口实现更松散的耦合。

关注我获取更多知识或者投稿

相关推荐
鸿蒙布道师1 小时前
鸿蒙NEXT开发动画案例2
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
HMS Core7 小时前
【FAQ】HarmonyOS SDK 闭源开放能力 — PDF Kit
华为·pdf·harmonyos
二蛋和他的大花8 小时前
HarmonyOS运动开发:如何集成百度地图SDK、运动跟随与运动公里数记录
华为·harmonyos
SuperHeroWu78 小时前
【HarmonyOS 5】鸿蒙页面和组件生命周期函数
华为·harmonyos·鸿蒙·自定义组件·页面·生命周期函数
HarmonyOS小助手9 小时前
Flutter适配HarmonyOS 5开发知识地图
harmonyos·鸿蒙·harmonyos next·鸿蒙flutter
搞瓶可乐10 小时前
鸿蒙ArkTs实战之截图保存图片到相册,详细教程,不使用SaveButton的方法,附上源码和效果图
华为·harmonyos·arkts·保存图片·操作沙箱·鸿蒙解决方案·媒体操作
__Benco11 小时前
OpenHarmony平台驱动开发(九),MIPI DSI
人工智能·驱动开发·harmonyos
深海的鲸同学 luvi12 小时前
【HarmonyOS 5】App Linking 应用间跳转详解
华为·harmonyos·applinking·应用间跳转
Bruce_Liuxiaowei12 小时前
HarmonyOS NEXT深度解析:自研框架ArkUI-X的技术革命与跨平台实践
华为·harmonyos
仓颉编程语言1 天前
南京大学OpenHarmony技术俱乐部正式揭牌 仓颉编程语言引领生态创新
harmonyos·鸿蒙·仓颉编程语言