【HarmonyOS】ArkTS language introduction and component approach application

        Starting from today, the blogger will open a new column to explain the popular technology "Hongmeng Development" on the market. For those who are new to this technology, it is necessary to understand Hongmeng first before learning Hongmeng Development. From you From the perspective of Hongmeng, what do you think it is? What is the significance of its appearance? Is Hongmeng just a mobile operating system? Can its emergence separate the world from Android and IOS? Can its future potential dominate the entire mobile phone market?

With such questions and curiosity about Hongmeng development, let’s start today’s understanding of the ArkTS language and mastering the components!

Table of contents

First introduction to ArkTS language

ArkUI basic components

Image (picture display component)

Text (text display component)

TextInput (text input box)

Button (button component)

Slider (slider component)

Column, Row (layout container)

ForEach (loop control)

List (list container)

ArkTS custom components


First introduction to ArkTS language

ArkTS is the preferred main application development language of HarmonyOS. It is based on TypeScript (TS for short), matches the ArkUI framework, and extends corresponding capabilities such as declarative UI and state management, allowing developers to develop in a simpler and more natural way. Cross-end application. To understand what ArkTS is, we must first understand the relationship between ArkTS, TypeScript and JavaScript, as follows:

Before learning ArkTS, it is recommended to first understand and master  JS and TS . If you master these two languages ​​and look back at ArkTS, you will be able to get started quickly. ArkTS is compatible with the TypeScript language and expands capabilities such as declarative UI, state management, and concurrent tasks. Before learning the ArkTS language, it is recommended that developers have the development capabilities of the ts language. Currently, ArkTS mainly extends the following capabilities based on ts:

Basic syntax :

ArkTS defines declarative UI description, custom components and the ability to dynamically extend UI elements. Together with the system components in the ArkUI development framework and their related event methods, property methods, etc., they form the main body of UI development.

Status management :

ArkTS provides a multi-dimensional state management mechanism. In the UI development framework, data associated with the UI can be used within a component, or can be passed between different component levels, such as between parent and child components, and between grandfather and grandchild components. It can also be passed within the global scope of the application or across devices. transfer. In addition, from the perspective of data transfer form, it can be divided into read-only one-way transfer and changeable two-way transfer. Developers can flexibly use these capabilities to achieve linkage between data and UI.

Rendering controls :

ArkTS provides rendering control capabilities. Conditional rendering can render the UI content in the corresponding state according to the different states of the application. Loop rendering can iteratively obtain data from a data source and create corresponding components during each iteration. Data lazy loading iterates data on demand from the data source and creates corresponding components during each iteration.

In the future, ArkTS will continue to evolve based on the needs of application development/operation, and gradually provide more features such as enhanced parallelism and concurrency capabilities, enhanced system types, distributed development paradigms, and more.

In terms of the layout structure of ArkTS , developers need to declare the corresponding elements on the page. The layout structure is usually hierarchical, representing the overall architecture of the user interface. A common page structure is as follows:

Page represents the root node of the page, and elements such as Column/Row are system components. For different page structures, ArkUI provides different layout components to help developers achieve corresponding layout effects. For example, Row is used to implement linear layout, etc. I will explain the corresponding layout in detail.

ArkUI basic components

Next, we will conduct a simple demonstration and application of the commonly used basic components of ArkUI to master the basic use of ArkUI.

Image (picture display component)

Declare the Image component and set the image source as follows:

Image(src: string|PixelMap|Resource)

1) string format, usually used to load network images, you need to apply for network access permission: ohos.permission.INTERNET

Image('https://xxx.png')

Open the module.json5 folder, configure the following requestPermissions options, and you can see the image appear.

2)PixelMap format, which can load pixel images and is commonly used in image editing

Image(pixelMapObject)

3) Resource format, loading local images, recommended

Image($r('app.media.mate'60.png)

Image($rawfile('mate60.png'))

Text (text display component)

Text(content?: string|Resource)

1) String format, fill in the text content directly

Text('text content')

2) Resource format, read local resource files

Text($r('app.string.width_label'))

Here we set up a dynamic text display:

TextInput (text input box)

TextInput( {placeholder?: ResourceStr, text?: ResourceStr} )

1) placeHolder: Prompt text when there is no input in the input box

TextInput({placeholder: 'Please enter your account number or mobile phone number'})

2) text: the current text content of the input box

TextInput({text: 'Text content'})

For example, we use the input box to dynamically change the size of an image as follows:

The following are descriptions of various types of input boxes:

name describe
Normal Basic input mode. Supports inputting numbers, letters, underscores, spaces, and special characters.
Password Password input mode. Supports inputting numbers, letters, underscores, spaces, and special characters.
Email Email address input mode. Supports numbers, letters, underscores, and @ characters.
Number Pure digital input mode.
PhoneNumber Phone number input mode. Supports inputting numbers, +, -, *, #, with no limit on length.

Button (button component)

Button(label?: ResourceStr)

1) Text button

Button('Click me')

2) Customize the button and nest other components within the Button

Button(){

        Image($r('app.media.search')).width(20).margin(10)

}

For example, if we use a button to dynamically change the size of an image, the operation is as follows:

Below are descriptions of the various types of buttons:

name describe
Capsule Capsule button (rounded corners default to half height).
Circle Round button.
Normal Normal button (without rounded corners by default).

Slider (slider component)

The function implementation of the slider component is very simple. You only need to set its function in the Slider and set its style externally:

Column, Row (layout container)

The parameters used for the corresponding alignment of the Column container and the Row container are shown in the following table:

Property method name illustrate parameter
justifyContent Set the alignment format of child elements in the main axis direction FlexAlign enum
alignItems Set the alignment format of child elements in the cross-axis direction Row container uses VerticalAlign enumeration
Column container uses HorizontalAlign enumeration

The main axis alignment function and its characteristics using FlexAlign in the Column container are as follows:

The main axis alignment function and its characteristics using FlexAlign in the Row container are as follows: 

The two are aligned on the cross axis as follows:

Column container: vertical layout, first from top to bottom, then from left to right.

Row container: Horizontal layout, first from left to right, then from top to bottom.

Examples of using Column and Row containers are given below:

@Entry
@Component

struct Index {
  // 设置状态变量
  @State ImageWidth: number = 150

  build() {
    Column() {
      Row(){
        Image($r('app.media.icon'))
          .width(this.ImageWidth)
          .interpolation(ImageInterpolation.High)
      }
      .width('100%')
      .height(400)
      .justifyContent(FlexAlign.Center)
      Row(){
        Text($r('app.string.width_label'))
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
          .fontColor('#008c8c')
        TextInput({text: this.ImageWidth.toString()})
          .backgroundColor('#fff')
          .width(200)
          .type(InputType.Number) // 只能输入数字类型
          .onChange(value=>{
            if (!value) {
              this.ImageWidth = 0
            }else {
              this.ImageWidth = parseInt(value)
            }
          })
      }
      .width('100%')
      .padding({left: 10, right: 10})
      .justifyContent(FlexAlign.SpaceBetween)
      Divider().width('91%')
      Row(){
        Button('缩小')
          .width(80)
          .fontSize(20)
          .onClick(()=>{
            if(this.ImageWidth >= 10){
              this.ImageWidth -= 10
            }
          })
        Button('放大')
          .width(80)
          .fontSize(20)
          .onClick(() => {
            if (this.ImageWidth <= 300) {
              this.ImageWidth += 10
            }
          })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceAround)
      .margin({top: 30, bottom: 30})

      Slider({
        min: 100,
        max: 300,
        value: this.ImageWidth,
        step: 10, // 步长
      })
        .width('90%')
        .blockColor('#36D')
        .trackThickness(5) // 滑动条的粗细
        .showTips(true) // 显示气泡百分比
        .onChange(value => {
          this.ImageWidth = value
        })
    }
    .width('100%')
    .height('100%')
  }
}

The resulting effect is as follows:

ForEach (loop control)

ForEach loops through the array and renders page components based on the contents of the array. The following is its basic format:

ForEach(
    arr: Array, // 要遍历的数据数组
    (item: any, index?: number) => {
        // 页面组件生成函数
    }
    keyGenerator?: (item: any, index?: number): string => {
        // 键生成函数,为数组每一项生产一个唯一标识,组件是否重新渲染的判断标准
    }
)

The following is a basic case of a component that generates a page through ForEach:

class Item {
  name: string
  image: ResourceStr
  price: number
  discount: number

  constructor(name: string, image: ResourceStr, price: number, discount = 0) {
    this.name = name
    this.image = image
    this.price = price
    this.discount = discount
  }
}

@Entry
@Component

struct Index {
  // 商品数据
  private items: Array<Item> = [
    new Item('华为', $r('app.media.icon'), 6999, 500),
    new Item('小米', $r('app.media.icon'), 7999),
    new Item('苹果', $r('app.media.icon'), 9999),
    new Item('三星', $r('app.media.icon'), 3999),
    new Item('oppo', $r('app.media.icon'), 1999),

  ]
  build(){
    Column({space: 4}){
      Row(){
        Text('商品列表')
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
      .margin({bottom: 20})

      ForEach(
        this.items,
        (item: Item) => {
          Row({space: 10}){
            Image(item.image)
              .width(100)
            Column({space: 4}){
              if (item.discount) {
                Text(item.name)
                  .fontSize(20)
                  .fontWeight(FontWeight.Bold)
                Text('原价:¥ '+ item.price)
                  .fontColor('#ccc')
                  .fontSize(14)
                  .decoration({type: TextDecorationType.LineThrough})
                Text('折扣价:¥ '+ (item.price - item.discount))
                  .fontColor('#F36')
                  .fontSize(18)
                Text('补贴:¥ '+ item.discount)
                  .fontColor('#F36')
                  .fontSize(18)
              }else {
                Text(item.name)
                  .fontSize(20)
                  .fontWeight(FontWeight.Bold)
                Text('¥ '+ item.price)
                  .fontColor('#F36')
                  .fontSize(18)
              }
            }
            .margin({left: 10})
            .height('100%')
            .alignItems(HorizontalAlign.Start)
          }
          .width('100%')
          .height(120)
          .borderRadius(20)
          .backgroundColor('#EFEFEF')
          .padding(20)
          .margin({bottom: 10})
        }
      )
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }
}

The results are presented as follows:

List (list container)

List is a complex container. When the amount of page content exceeds the screen, its list item ListItem will automatically provide a scrolling function. Of course, the list items can be arranged vertically or horizontally. Its basic format code is as follows:

List({space: 10}){
    ForEach([1, 2, 3, 4], item => {
        ListItem(){
            // 列表项内容,只能包含一个根组件
            Text('ListItem')
        }
    })
}
.width('100%')
.listDirection(Axis.Vertical) // 列表方向,默认纵向(垂直)

We nest a List container outside ForEarch, and we nest ListItem inside ForEach to achieve page scrolling:

The final effect is as follows:

ArkTS custom components

ArtTS provides some ways to customize components and functions to separate complex codes, facilitate the maintainability and readability of the code, and enhance the robustness of the code. The following are methods related to custom components in ArkTS:

Custom components : Custom components are very simple. They can be written in an ets. Just process part of the code and set up a new struct constructor. You can also extract the code separately to form a new file. The above case is as follows The header component is extracted to form a new component Header, and then the Header component can be referenced at the location where the header code was originally written:

Custom function : A custom function can separate the long code into a function, and then call the function we set at the original location. The custom function can be defined globally or within a component, as follows:

If you want to set a custom function in the component, you need to set it at the same level as the build() function and remove the function. Then the location where the function is referenced needs to be pointed to by this:

@Styles decorator : used to set the public style of the component, which can be defined globally or within the component, in the same way as a custom function, as follows:

@Extend decorator : It can only be defined globally and is used to set the unique properties of the component. The usage method is the same as above:

// 继承模式,只能写在全局
@Extend(Text) function priceText() {
  .fontSize(18)
  .fontColor('#F36')
}

Guess you like

Origin blog.csdn.net/qq_53123067/article/details/135307508