DEV Community

SameX
SameX

Posted on

Custom Components in HarmonyOS Next Page Development

Custom Components in HarmonyOS Next Page Development

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system and summarize them based on practical development practices. It mainly serves as a medium for technical sharing and communication. There may inevitably be some errors or omissions. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.

In the process of page development for HarmonyOS Next, custom components are like those specially crafted unique modules when building with Lego blocks. They provide developers with a high degree of flexibility and reusability. Next, let's take an in-depth look at the importance of custom components in ArkTS, the creation method, and how to ensure that they can be perfectly adapted to different screens.

Why Do We Need Custom Components? (Encapsulating and Reusing Components in ArkTS)

In large-scale application development, the reusability and maintainability of the code are of vital importance. Imagine that if you need to display a button with a specific style on different pages each time, and you have to rewrite the code from scratch, not only will the workload be huge, but it will also be extremely difficult to maintain and modify in the later stage. This is where custom components come in handy.

In ArkTS, custom components can encapsulate commonly used UI elements or functional logic to form independent and reusable modules. In this way, when we need the same function or style on multiple pages, we only need to reference this custom component instead of writing the code repeatedly. This not only greatly improves development efficiency but also ensures the consistency of the style of the entire application. At the same time, when a certain function needs to be modified, we only need to make adjustments in the custom component, and all the pages that reference this component will be updated automatically, effectively reducing the maintenance cost.

For example, in an e-commerce application, the display of product list items appears on multiple pages, including the product search results page and the category product list page. By encapsulating the product list item into a custom component, we can easily reuse it on different pages. And when we need to adjust the style or interaction logic of the product list item, we only need to modify this one component, avoiding the cumbersome operation of modifying it one by one on multiple pages.

How to Create Reusable Layout Components (Example Code + Adaptive Layout Solution)

Next, through a simple example of a card-style layout component, let's see how to create reusable layout components in ArkTS and incorporate an adaptive layout solution.

@Component
struct CardComponent {
    @Prop title: string
    @Prop content: string
    @Prop image: Resource

    build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
            Image(this.image).width(100).height(100).objectFit(ImageFit.Contain)
            Text(this.title).fontSize(18).fontWeight(500).margin({ top: 10 })
            Text(this.content).fontSize(14).opacity(0.8).margin({ top: 5 })
        }
          .width('90%')
          .backgroundColor('#FFFFFF')
          .padding(20)
          .borderRadius(16)
          .shadow({
                color: '#00000040',
                offset: { x: 0, y: 4 },
                blurRadius: 10
            })
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we have created a custom component named CardComponent. It accepts three properties, title, content, and image, which are used to display the title, content, and image of the card. Inside the component, the Flex component is used for layout, achieving a vertical arrangement. By setting width('90%'), the width of the card adapts to the parent container. At the same time, styles such as background color, rounded corners, and shadows are set to make the card look more beautiful.

In actual use, we can reference this component like this:

@Entry
@Component
struct MainPage {
    build() {
        Column() {
            CardComponent({
                title: 'Example Title',
                content: 'This is an example content',
                image: $r('app.media.exampleImage')
            })
            CardComponent({
                title: 'Another Title',
                content: 'Different example content',
                image: $r('app.media.anotherImage')
            })
        }
          .width('100%')
          .height('100%')
          .justifyContent(FlexAlign.Center)
    }
}
Enter fullscreen mode Exit fullscreen mode

In this way, in the MainPage, we have easily reused the CardComponent component to display two cards with different contents.

Skills for Encapsulating Responsive + Adaptive Components (Ensuring Components are Adaptable to Different Screens)

To ensure that custom components can be perfectly adapted to different screens, we need to combine the techniques of responsive and adaptive layouts. Now, let's upgrade the above CardComponent to make it responsive and adaptive.

@Component
struct ResponsiveCardComponent {
    @Prop title: string
    @Prop content: string
    @Prop image: Resource
    @State currentBreakpoint: string ='sm'

    build() {
        GridRow({ breakpoints: { value: ['600vp'], reference: BreakpointsReference.WindowSize } }) {
            GridCol({ span: { sm: 12, md: 6 } }) {
                Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
                    Image(this.image).width(this.currentBreakpoint ==='sm'? '100%' : '60%').height(this.currentBreakpoint ==='sm'? 100 : 150).objectFit(ImageFit.Contain)
                    Text(this.title).fontSize(this.currentBreakpoint ==='sm'? 16 : 20).fontWeight(500).margin({ top: 10 })
                    Text(this.content).fontSize(this.currentBreakpoint ==='sm'? 12 : 16).opacity(0.8).margin({ top: 5 })
                }
                  .width('100%')
                  .backgroundColor('#FFFFFF')
                  .padding(20)
                  .borderRadius(16)
                  .shadow({
                        color: '#00000040',
                        offset: { x: 0, y: 4 },
                        blurRadius: 10
                    })
            }
        }
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
            })
    }
}
Enter fullscreen mode Exit fullscreen mode

In this upgraded component ResponsiveCardComponent, we have introduced the GridRow and GridCol components to achieve a responsive layout. By setting breakpoints, under different breakpoints (here, the sm and md breakpoints are distinguished with 600vp as the boundary), the GridCol component occupies different numbers of columns, thus adjusting the width of the card on the page. At the same time, according to the change of the breakpoint, we also dynamically adjust the width and height of the image and the font size of the text, so that the component can maintain a good display effect on different screen sizes. For example, under a small screen (the sm breakpoint), the width of the image is 100%, the height is 100, and the text font is smaller; while under a large screen (the md breakpoint), the width of the image is 60%, the height is 150, and the text font is larger to make full use of the screen space.

In practical applications, such custom components can present appropriate layouts and styles on various devices, providing users with a consistent and high-quality experience. Whether it is a mobile phone, a tablet, or a large-screen device, it can be adjusted adaptively to meet the display requirements of different devices.

By making reasonable use of custom components and combining the techniques of responsive and adaptive layouts, we can build efficient, flexible, and screen-adaptable application interfaces in the page development of HarmonyOS Next. It is hoped that these contents can help developers better apply custom components in actual projects and improve development efficiency and application quality.

Top comments (0)