DEV Community

HarmonyOS
HarmonyOS

Posted on

How does uni-app embed Hongmeng native components?

Read the original article:How does uni-app embed Hongmeng native components?

How does uni-app embed Hongmeng native components?

Problem description

How to embed Hongmeng native components in uni-app?

Solution

Hongmeng system has many native components. Starting from HBuilderX version 4.62, uni-app can be registered as a native component supported by WebView through uts plug-in, and supports same-layer rendering. Currently, Hongmeng native components only support definitions in ets files, and uts plug-in supports importing ets files.

Register Hongmeng native components
Interface definition

export interface NativeEmbedEvent {
  detail: object;
}

export interface NativeEmbedBuilderOptions {
  width: number;
  height: number;
  on?: Map<string, (event?: NativeEmbedEvent) => void>;
}

export interface DefineNativeEmbedOptions<
  T extends NativeEmbedBuilderOptions = NativeEmbedBuilderOptions
> {
  builder: (options: T) => void;
}

export declare function defineNativeEmbed<
  T extends NativeEmbedBuilderOptions = NativeEmbedBuilderOptions
>(tag: string, options: DefineNativeEmbedOptions<T>): void;
Enter fullscreen mode Exit fullscreen mode

code example

import { NativeEmbedBuilderOptions, defineNativeEmbed } from "@dcloudio/uni-app-runtime"

interface ButtonBuilderOptions extends NativeEmbedBuilderOptions {
  label: string
}

interface ButtonClickEventDetail {
  text: string
}


@Component
struct ButtonComponent {
  @Prop label: string
  onButtonClick?: Function

  build() {
    Button(this.label)
      .width('100%')
      .height('100%')
      .onClick(() => {
        if (this.onButtonClick) {
          const detail = {
            text: 'test'
          } as ButtonClickEventDetail
          this.onButtonClick({
            detail
          })
        }
      })
  }
}

@Builder
function ButtonBuilder(options: ButtonBuilderOptions) {
  ButtonComponent({
    label: options.label,
    onButtonClick: options?.on?.get('click')
  })
    .width(options.width)
    .height(options.height)
}

defineNativeEmbed('button', {
  builder: ButtonBuilder
})
Enter fullscreen mode Exit fullscreen mode

The above code registers a native component ButtonComponent with uni-app in the ets file, with the tag name button. Import this ets file in the uts plugin to take effect.
Associate IR Order

Written by Emine Inan

Top comments (0)