鴻蒙 ArkUI-自定義組件

一、定義全局組件

在項(xiàng)目的目錄結(jié)構(gòu)中新增,components目錄,并且創(chuàng)建xxx.ets組件文件


image.png

代碼如下(標(biāo)題欄):

@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 })
  }
}

二、定義局部組件

在當(dāng)前代碼文件內(nèi)部定義組件,無需使用export關(guān)鍵字,直接將代碼寫在最上面即可,這種適用該組件只被當(dāng)前ets文件所調(diào)用,否則就得定義成全局的。

@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 })
  }
}

三、使用組件

在文件最頂部導(dǎo)入組件

//1.導(dǎo)入TitleBar組件
import { TitleBar } from '../components/TitleBar'

在build() 方法中調(diào)用該組件

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

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

        List({ space: 8 }) {
          ForEach(this.items, (item: Item, index) => {
            ListItem() {
              this.ItemCard(item)
            }
          })
        }
        .layoutWeight(1)
      }
      .fillScreen()
    }
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容