HarmonyOS--@Extend装饰器:定义扩展组件样式

目录

概要

说明

语法:

使用:

使用场景

点击参考文档

小结


概要

在前文我们使用了@Styles装饰器用于样式,因此,在@Styles装饰器基础上提供了@Extend装饰器,可以用于扩展原生组件样式。


说明

语法:

@Extend(UIComponentName) function functionName { ... }

使用:

1.与@Styles不同,@Extend仅支持定义在全局,不支持在组件内部定义。
只能在当前文件内使用,不支持export。

2.@Extend装饰的方法的参数可以为function。

@Extend(Button) function extendButtonStyle(){
    ...
}

3.和@Styles不同,@Extend装饰的方法支持参数,我们可以在调用时传递参数。

@Extend(Text) function fancy (fontSize: number) {
  .fontColor(Color.Red)
  .fontSize(fontSize)
}

@Entry
@Component
struct FancyUse {
  build() {
    Row({ space: 10 }) {
      Text('原神')
        .fancy(10)
      Text('牢底')
        .fancy(11)
    }
  }
}


使用场景

需求:两个按钮,复用按钮的样式:
    .width(100)
    .height(40)
    .borderRadius(10)

@Entry
@Component
struct ExtendPageC3 {
  build() {
    Column() {
      Row({ space: 30 }) {
        Button('确认')
          //引用Extend扩展样式
          .extendButtonStyle(Color.Green,()=>console.info('确认'))

         /* .type(ButtonType.Normal)
          .backgroundColor(Color.Green)
          .width(150)
          .height(60)
          .borderRadius(10)
          .onClick(() => console.log('确认'))*/

        Button('取消')
          //引用Extend扩展样式
          .extendButtonStyle(Color.Grey,()=>console.info('取消'))

          /*.type(ButtonType.Normal)
          .backgroundColor(Color.Grey)
          .width(150)
          .height(60)
          .borderRadius(10)
          .onClick(() => console.info('取消'))*/

      }
    }.width('100%')
    .height('100%')
    //对齐方式
    .justifyContent(FlexAlign.Center)
  }
}

//Extend扩展样式
@Extend(Button) function extendButtonStyle(color: Color, callback: () => void) {
  .width(150)
  .height(50)
  .borderRadius(10)
  .type(ButtonType.Normal)
  .backgroundColor(color)
  .onClick(callback)
}

点击参考文档


小结

1. @Extend方法只能定义在全局,使用范围目前只限于当前的.ets文件。
2. @Extend方法用于特定类型的组件,因此可包含该组件的专有属性方法和专有事件方法。
3. @Extend方法支持参数。

4.通过@Extend组合样式后,使得代码更加简洁,增强可读性。

  • 14
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值