概述
在 HarmonyOS ArkUI 开发中, @Builder 和 @Component 都用于封装可复用的 UI 片段,但它们的定位和使用方式有本质区别。开发者经常混淆两者,导致代码冗余或渲染异常。

说明
- @Builder :用于封装可复用的 UI 片段,是方法级别的复用,不能独立渲染
- @Component :用于定义独立的组件,可以独立渲染和管理自己的状态

最佳实践

@Builder 不能作为独立组件使用,一般用于简单 UI 片段

@Builder
function IconText(icon: string, text: string) {
  Row() {
    Image(icon).width(24).height(24)
    Text(text).fontSize(14)
  }
  .width('100%')
  .padding(12)
}

@Component
struct SettingsPage {
  build() {
    Column() {
      IconText('wifi.svg', 'Wi-Fi')
      IconText('bluetooth.svg', 'Bluetooth')
      IconText('bell.svg', 'Notifications')
    }
  }
}

 

@Component 定义独立组件,一般用于复杂组件

@Component
struct UserCard {
  @Prop name: string;
  @Prop avatar: string;
  @Prop status: 'online' | 'offline';
  
  build() {
    Row() {
      Image(this.avatar)
        .width(48)
        .height(48)
        .borderRadius(24)
      
      Column() {
        Text(this.name).fontSize(16)
        Text(this.status).fontSize(12).fontColor(this.status === 'online' ? '#00ff00' : '#999')
      }
    }
    .width('100%')
    .padding(16)
  }
}

@Entry
@Component
struct ContactList {
  @State contacts = [
    { name: 'Alice', avatar: 'avatar1.png', status: 'online' },
    { name: 'Bob', avatar: 'avatar2.png', status: 'offline' }
  ]
  
  build() {
    Column() {
      ForEach(this.contacts, (item) => {
        UserCard({ 
          name: item.name, 
          avatar: item.avatar, 
          status: item.status 
        })
      })
    }
  }
}

 

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐