OpenHarmony component reuse example

This article is reproduced from " #2023BlindBox+Code# OpenHarmony Component Reuse Example ", author zhushangyuan_

  • Abstract: When developing applications, custom components in some scenarios have the same component layout structure, with only differences in state variables and other carrying data. Such components are cached and reused directly when the component needs to be used.
  • Reduced creation and rendering time can improve frame rate and user performance experience. This article will introduce how to use component reusability when developing OpenHarmony applications. Keywords: OpenHarmony HarmonyOS HarmonyOS ForEach LazyForEach Loop rendering

overview

When developing applications, custom components in some scenarios have the same component layout structure, with only differences in state variables and other carrying data. Such components are cached and reused directly when the component needs to be used.

Reduce the time spent on repeated creation and rendering, thereby improving the loading speed and responsiveness of application pages. During OpenHarmony application development, when a custom component is decorated with the @Reusable decorator, it means that the custom component can be reused. After the reusable component created under the parent custom component is removed from the component tree, it will be added to the reusable node cache of the parent custom component.

When the parent custom component creates the reusable component again, it will quickly create the reusable component from the cache by updating the reusable component. This is the component reuse mechanism of OpenHarmony. This article will introduce how to use component reusability when developing OpenHarmony applications.

Environmental preparation

Prepare a DevEco Studio, and use a real device or Simulator to verify. For more information about DevEco Studio, please visit: HUAWEI DevEco Studio and SDK Download and Upgrade | HarmonyOS Developer .

Component reuse interface

The aboutToReuse method is defined in the life cycle of the custom component in the OpenHarmony SDK file ets\component\common.d.ts, as follows:

The life cycle callback function of a custom component is used to notify the user of the life cycle of the custom component. These callback functions are private and are called by the development framework at a specific time during runtime. These callback functions cannot be manually called from the application .

When a reusable custom component is added to the node tree from the reuse cache, the aboutToReuse lifecycle callback is triggered and the component's construction parameters are passed to aboutToReuse. The parameter of the aboutToReuse function is a dictionary type, the key is the variable name of the component's construction parameter, and the value is the actual value of the component's construction parameter.

The declaration cycle function starts from API version 10, and this interface supports the use in ArkTS cards.

declare class CustomComponent extends CommonAttribute {
       
       
......
 /**
   * aboutToReuse Method
   *
   * @param { { [key: string]: unknown } } params - Custom component init params.
   * @syscap SystemCapability.ArkUI.ArkUI.Full
   * @crossplatform
   * @since 10
   */
  aboutToReuse?(params: {
       
        [key: string]: unknown }): void;
......
}

development practice

Let's look at a practical use case of component reuse. In the example, a picture list page will be created, using lazy loading LazyForEach, and component reusability.

Create a data source

First, a business object class MyImage is created, which contains an image_id image number and image_path image path. Depending on the actual business, there will be differences. This example is for demonstration only.

Then, create a data source class ImageListDataSource, and construct a list object imageList.

As you can see, 10,000 records are constructed. There are 50 images under the /resources/images folder of the project.

Each record contains a number from 0 to 9999.

In the record, there is also a picture path one by one. For different records, the number will not be repeated, and the picture path may be repeated.

So far, the data source class has been created.

export class MyImage {
       
       
  image_id: string
  image_path: string
  constructor(image_id: string, image_path: string) {
       
       
    this.image_id = image_id
    this.image_path = image_path
  }
}

export class ImageListDataSource extends BasicDataSource {
       
       
  private imageList: MyImage[] = []
  public constructor() {
       
       
    super()
    for (let i = 0;< 10000; i++) {
       
       
      let imageStr = `/resources/images/photo${(i % 50).toString()}.jpg`
      this.imageList.push(new MyImage(i.toString(), imageStr))
    }
  }
  public totalCount(): number {
       
       
    return this.imageList.length
  }
  public getData(index: number): MyImage {
       
       
    return this.imageList[index]
  }
......
}

Create reusable components

After creating the data source class, let's look at the code of the reusable component.

Use the decorator @Reusable to mark whether a component is a reusable component.

The reusable component we created has a state variable @State item. When constructing the custom component, the parent component will pass construction data to the child and parent.

It is also necessary to implement the component reuse statement cycle callback function aboutToReuse. In this function, the construction data is passed to the reusable component through params.

In the function aboutToReus, we add a separate print function to output a log record when the component is reused.

It should be noted that, under normal circumstances, in the aboutToReuse function, do not perform any time-consuming operations except constructing parameters to pass values.

In the build() method of the reusable component, render a line for each record, including the picture, picture number and picture path.

The image number can identify which piece of data is rendered, and is used to verify that the component reuses the correct component.

@Reusable
@Component
struct MyListItem {
       
       
  @State item: MyImage = new MyImage('', '')

  aboutToReuse(params) {
       
       
    this.item = params.item
    Logger.info(TAG, 'aboutToReuse-,item=' + this.item.toString())
  }

  build() {
       
       
    Row({ space: 10 }) {
       
       
      Image(this.item.image_path)
        .width(50)
        .height(50)
        .borderRadius(5)
        .autoResize(false)
        .syncLoad(true)
      Blank()
      Text(this.item.image_id)
        .fontColor(Color.Black)
        .fontSize(15)
      Blank()
      Text(this.item.image_path)
        .fontColor(Color.Black)
        .fontSize(15)
    }
  }
}

entry component

In our @Ent

*/-·- In the component, in the List parent component, you can call the reusable component MyListItem. Complete parent-child component parameter passing through { item: item } .

The reuseId parameter is optional and is used to mark the reuse type of the reusable component. Annotations for attribute parameters are as follows:

  /**
   * Reuse id is used for identify the reuse type for each custom node.
   * 
   * @param { string } id - The id for reusable custom node.
   * @syscap SystemCapability.ArkUI.ArkUI.Full
   * @crossplatform
   * @since 10
   */
  reuseId(id: string)

The sample code of the entry component is as follows:

@Entry
@Component
struct Index {
       
       
  private data: ImageListDataSource = new ImageListDataSource()

  build() {
       
       
    List({ space: 3 }) {
       
       
      LazyForEach(this.data, (item: MyImage) => {
       
       
        ListItem() {
       
       
          MyListItem({
       
        item: item })
            // .reuseId(item.image_id)
        }
      }, item => item)
    }
  }
}

Precautions

You can visit the site developtools_ace_ets2bundle: -- - Gitee.com to see some examples of component reuse, these are examples for testing.

The name of the decorator before @Reusable is @Recycle, and the old name is not used anymore. The ForEach rendering control has the feature of full expansion and cannot trigger component reuse.

Summarize

This article introduces how to use the component reuse capability when developing OpenHarmony applications, provides code examples, and hopes to help developers and friends who are concerned about component reuse.

If you have any questions, welcome to exchange and discuss.

References

[1] Sample chat application

[2] Life cycle of custom components

[3] Component reuse scenario

[4] Some examples of component reuse

Guess you like

Origin blog.csdn.net/OpenHarmony_dev/article/details/132560202