1.在 ets 文件夹下新建组件 components/HmNavBar.ets

@Preview
@Component
export struct HmNavBar {
  title: string = "" //标题
  showBackIcon: boolean = true //返回
  onBackClick: () => void = () => {}
  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Row() {
        if(this.showBackIcon){
          Text() {
            SymbolSpan($r('sys.symbol.chevron_left'))
              .fontSize(24)
              .fontWeight(FontWeight.Bold)
              .fontColor(['#2a2929'])
          }
          .position({
            left: 10,
          })
          .onClick(() => {
            this.onBackClick()
          })
        }
        if(this.title) {
          Text(this.title)
            .fontColor('#2a2929')
            .fontSize(18)
            .fontWeight(FontWeight.Bold)

        }
      }
      .justifyContent(FlexAlign.Center)
      .alignItems(VerticalAlign.Center)
      .width('100%')
      .height('100%')
    }
    .backgroundColor('#fff')
    .width('100%')
    .height(50)
    .padding(10)
  }
}

2.使用自定义组件

import {HmNavBar} from '../../components/HmNavBar'
@Entry
@Component
struct Index {
  build() {
    Column(){
      HmNavBar({title:'商品详情',showBackIcon:true,onBackClick:()=>{
        this.getUIContext().getRouter().back(
      )}})
    }
    .height('100%')
    .width('100%')
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐