HarmonyOS 与 ArkTS | 自定义组件

HarmonyOS 与 ArkTS | 自定义组件

原效果:

代码:

@Entry
@Component
struct Index {
  build() {
    Column(){
      Row(){
        Column(){
          this.ItemCard($rawfile('ic_controlcenter_eyeconfort_filled.png'))
          Divider()
          .margin({top: 10,bottom: 10})
          this.ItemCard($rawfile('ic_controlcenter_nfc_filled.png'))
        }
      }
      .margin({top: 20})
      .width('80%')
      .height('150')
      .backgroundColor(Color.White)
      .borderRadius(10)
      .shadow({radius: 30,color: Color.Black})
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#E7E8EB')

  }
  // 局部自定义构建函数
@Builder ItemCard(src: Resource){
  Row(){
    Image(src)
      .width('50')
      .interpolation(ImageInterpolation.High)// 图片插值函数,让图片更清晰
    Toggle({ type: ToggleType.Switch, isOn: false })
      .selectedColor('#007DFF')
      .switchPointColor('#FFFFFF')
      .onChange((isOn: boolean) => {
        console.info('Component status:' + isOn)
      })
  }
  .width('100%')
  .justifyContent(FlexAlign.SpaceEvenly)
}
}

如何用一种通用的方式为我们的页面添加顶栏?

答案是创建自定义组件,创建以下代码文件:

@Component
export struct Header{
  private title: ResourceStr
  build(){
    Row(){
      Image($rawfile('ic_public_arrow_left.png'))
        .width('30')
      Text(this.title)
        .fontSize('30')
        .fontWeight(FontWeight.Bold)
      Blank()
      Image($rawfile('ic_public_refresh.png'))
        .width('30')
    }
    .width('100%')
    .height('48')
  }
}

在刚才的页面文件中导入组件(通常会自动导入):import { Header } from '../components/CommonComponents'

然后在合适的位置调用组件即可。

项目结构:

最终效果:

代码:

import { Header } from '../components/CommonComponents'
@Entry
@Component
struct Index {
  build() {
    Column(){
      Header({title: '设置'})
      .backgroundColor(Color.White)
      Row(){
        Column(){
          this.ItemCard($rawfile('ic_controlcenter_eyeconfort_filled.png'))
          Divider()
          .margin({top: 10,bottom: 10})
          this.ItemCard($rawfile('ic_controlcenter_nfc_filled.png'))
        }
      }
      .margin({top: 20})
      .width('80%')
      .height('150')
      .backgroundColor(Color.White)
      .borderRadius(10)
      .shadow({radius: 30,color: Color.Black})
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#E7E8EB')

  }
  // 局部自定义构建函数
@Builder ItemCard(src: Resource){
  Row(){
    Image(src)
      .width('50')
      .interpolation(ImageInterpolation.High)// 图片插值函数,让图片更清晰
    Toggle({ type: ToggleType.Switch, isOn: false })
      .selectedColor('#007DFF')
      .switchPointColor('#FFFFFF')
      .onChange((isOn: boolean) => {
        console.info('Component status:' + isOn)
      })
  }
  .width('100%')
  .justifyContent(FlexAlign.SpaceEvenly)
}
}

posted @ 2024-03-17 17:05  JayHsu_蔚蓝审敛法  阅读(19)  评论(0编辑  收藏  举报