鸿蒙 ArkUI-自定义组件

2024-06-05  本文已影响0人  差点长成一枚帅哥

一、定义全局组件

在项目的目录结构中新增,components目录,并且创建xxx.ets组件文件


image.png

代码如下(标题栏):

@Component
export struct TitleBar {
  private title: ResourceStr

  build() {
    Row() {
      Image($r('app.media.back'))
        .width(30)
      Text(this.title)
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
      Blank()
      Image($r('app.media.refresh'))
        .width(30)
    }
    .width('100%')
    .margin({ bottom: 20 })
  }
}

二、定义局部组件

在当前代码文件内部定义组件,无需使用export关键字,直接将代码写在最上面即可,这种适用该组件只被当前ets文件所调用,否则就得定义成全局的。

@Component
struct TitleBar {
  private title: ResourceStr

  build() {
    Row() {
      Image($r('app.media.back'))
        .width(30)
      Text(this.title)
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
      Blank()
      Image($r('app.media.refresh'))
        .width(30)
    }
    .width('100%')
    .margin({ bottom: 20 })
  }
}

三、使用组件

在文件最顶部导入组件

//1.导入TitleBar组件
import { TitleBar } from '../components/TitleBar'

在build() 方法中调用该组件

 build() {
    Row() {
      Column({ space: 8 }) {

        //2.直接使用全局组件
        TitleBar({ title: '商品列表' })

        List({ space: 8 }) {
          ForEach(this.items, (item: Item, index) => {
            ListItem() {
              this.ItemCard(item)
            }
          })
        }
        .layoutWeight(1)
      }
      .fillScreen()
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读