#鸿蒙通关秘籍#如何在HarmonyOS NEXT中使用@Builder自定义构建函数以封装结构?

HarmonyOS
2024-11-27 13:15:08
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
WebWhiz

通过@Builder在HarmonyOS NEXT中可以自定义构建函数,将需要复用的结构、样式和事件进行封装,提升代码复用性。

import text from '@ohos.graphics.text'

@Builder function TextItem(text: string){
  Text(text)
    .fontSize(18)
    .fontColor(Color.Red)
    .backgroundColor('#ccc')
    .lineHeight(30)
    .width('100%')
    .textAlign(TextAlign.Center)
    .onClick(()=>{
      AlertDialog.show({
        message: text
      })
    })
}
@Entry
@Component
struct Index {
  build() {
    Column(){
      TextItem('111')
      TextItem('222')
      TextItem('333')
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

以这种方式,可以方便地重复使用相同的组件结构和行为,改善代码的可维护性。

分享
微博
QQ
微信
回复
2024-11-27 14:30:04


相关问题
@Builder自定义构建函数如何回参?
1156浏览 • 1回复 待解决