五、自定义组件

发布时间 2023-12-04 15:32:09作者: 创客未来

1.创建自定义组件

在ArkUI中,UI显示的内容均为组件,由框架直接提供的称为系统组件,由开发者定义的称为自定义组件。在进行UI界面开发时,通常不是简单的将系统组件进行组合使用,而是需要考虑代码可复用性、业务逻辑与UI分离,后续版本演进等因素。因此,将UI和部分业务逻辑封装成自定义组件是不可或缺的能力。

自定义组件具有以下特点:

可组合:允许开发者组合使用系统组件、及其属性和方法。

可重用:自定义组件可以被其他组件重用,并作为不同的实例在不同的父组件活容器中使用。

数据驱动UI更新:通过状态变量的改变,来驱动UI的刷新。

/**
 * author:创客未来
 * copyright:com.ckFuture.hrb
 */
/**
 * 1:组件必须使用 @Component 装饰器
 * 2: @Entry 装饰哪个组件、哪个就呈现在页面上
 * 3: 被@Entry装饰的入口组件,build()中必须有且仅有一个**根容器**组件
 *    其他自定义组件,build()
 */
@Entry
@Component
struct Demo2 {
  @State message: string = '诗词学习'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        itemComponent()
        itemComponent({content:'我是传递字符串'})
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct itemComponent{
  // 自定义组件可以使用私有化变量(组件内部的变量都是私有化的,默认就是私有化) 传递参数
  private content: string = '默认字符串'
  build(){
    Row(){
      Image($r('app.media.icon'))
        .width(20)
        .height(20)
        .margin(15)
      Text(this.content)
    }
    .backgroundColor(Color.Pink)
    .borderRadius(25)
    .margin({
      top:15
    })
  }
}

 

 组件内部点击事件

/**
 * author:创客未来
 * copyright:com.ckFuture.hrb
 */
import FaultLogger from '@ohos.faultLogger'
/**
 * 1:组件必须使用 @Component 装饰器
 * 2: @Entry 装饰哪个组件、哪个就呈现在页面上
 * 3: 被@Entry装饰的入口组件,build()中必须有且仅有一个**根容器**组件
 *    其他自定义组件,build()
 */
@Entry
@Component
struct Demo2 {
  @State message: string = '诗词学习'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        itemComponent()
        itemComponent({content:'我是传递字符串'})
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct itemComponent{
  // 自定义组件可以使用私有化变量(组件内部的变量都是私有化的,默认就是私有化) 传递参数
  private content: string = '默认字符串'
  // 哪种情况可以驱动UI更新,@State
  @State isDone: boolean = false
  build(){
    Row(){
      Image(this.isDone?$r('app.media.iconOk'):$r('app.media.icon'))
        .width(20)
        .height(20)
        .margin(15)
      Text(this.content)
    }
    .backgroundColor(Color.Pink)
    .borderRadius(25)
    .margin({
      top:15
    })
    .onClick(()=>{
      //点击这一行修改图片
      this.isDone = !this.isDone
    })
  }
}

 

点击自定义组件,文字变化效果

@Component
struct itemComponent{
  // 自定义组件可以使用私有化变量(组件内部的变量都是私有化的,默认就是私有化) 传递参数
  private content: string = '默认字符串'
  // 哪种情况可以驱动UI更新,@State
  @State isDone: boolean = false
  build(){
    Row(){
      Image(this.isDone?$r('app.media.icon'):$r('app.media.icon'))
        .width(20)
        .height(20)
        .margin(15)
      Text(this.content)
        .decoration({
          type:this.isDone?TextDecorationType.LineThrough:TextDecorationType.None
        })
    }
    .backgroundColor(Color.Pink)
    .borderRadius(25)
    .margin({
      top:15
    })
    .onClick(()=>{
      //点击这一行修改图片
      this.isDone = !this.isDone
    })
  }
}