HarmonyOS 鸿蒙Next中如何在实现自定义组件?

HarmonyOS 鸿蒙Next中如何在实现自定义组件? 问题描述:需要封装一个带图标和文字的按钮组件。

3 回复

回答内容:使用@Component装饰器定义自定义组件。

示例代码:

/**
 * @author J.query
 * @date 2025/12/23 11:17
 * @email j-query@foxmail.com
 * Description:
 */

[@Component](/user/Component)
struct IconTextButton {
  @Prop icon: string;
  @Prop text: string;
  @State pressed: boolean = false;

  build() {
    Row() {
      Image(this.icon)
        .width(24)
        .height(24)
      Text(this.text)
        .fontSize(16)
        .fontWeight('bold')
    }
    .backgroundColor(this.pressed ? '#007DFF' : '#FFFFFF')
    .borderRadius(8)
    .padding({ left: 12, right: 12, top: 8, bottom: 8 })
    .onTouch((event) => {
      if (event.type === TouchType.Down) {
        this.pressed = true;
      } else if (event.type === TouchType.Up) {
        this.pressed = false;
      }
    })
  }
}

@Entry
[@Component](/user/Component)
struct UseCustomComponent {
  build() {
    Column() {
      IconTextButton({ icon: 'icons/heart.png', text: '点赞' })
    }
    .width('100%')
    .height('100%')
  }
}

效果:显示带图标的按钮,按压时背景变色。

cke_1319.png cke_2662.png

更多关于HarmonyOS 鸿蒙Next中如何在实现自定义组件?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,自定义组件通过ArkTS的@Component装饰器实现。开发者需定义struct结构,并使用@Builder@BuilderParam等装饰器构建UI。组件状态管理使用@State@Prop等装饰器。通过继承或组合现有组件,可封装特定功能与样式。

在HarmonyOS Next中实现自定义组件(如带图标和文字的按钮),核心是使用ArkTS的@Component装饰器。以下是关键步骤和代码示例:

  1. 创建组件结构:使用@Component定义可复用UI单元。
[@Component](/user/Component)
struct IconButton {
  // 定义组件参数
  private icon: Resource = $r('app.media.icon');
  private text: string = '按钮';
  private onClick: () => void = () => {};

  build() {
    // 构建UI布局
    Row() {
      Image(this.icon)
        .width(20)
        .height(20)
      Text(this.text)
        .fontSize(16)
    }
    .padding(10)
    .backgroundColor(Color.Blue)
    .onClick(() => {
      this.onClick();
    })
  }
}
  1. 参数传递优化:使用@Prop@Link装饰器实现动态数据绑定。
[@Component](/user/Component)
struct IconButton {
  [@Prop](/user/Prop) icon: Resource;
  [@Prop](/user/Prop) text: string;
  private onClick: () => void;

  // 组件实现
}
  1. 使用自定义组件:在页面中直接调用并传递参数。
@Entry
[@Component](/user/Component)
struct Index {
  build() {
    Column() {
      IconButton({
        icon: $r('app.media.home'),
        text: '首页',
        onClick: () => {
          console.log('按钮被点击');
        }
      })
    }
  }
}
  1. 样式扩展:可通过@Styles@Extend装饰器定义可复用样式,或在组件参数中添加尺寸、颜色等配置项增强灵活性。

注意事项:

  • 组件应遵循单一职责原则,保持功能聚焦
  • 合理使用状态管理装饰器(@State@Prop等)
  • 通过通用参数设计提高组件可配置性

这种封装方式实现了UI与逻辑的分离,符合HarmonyOS Next的组件化开发范式。

回到顶部