说明: 从 API version 9 开始,该装饰器支持在 ArkTS 卡片中使用。
装饰器使用说明
语法
@Extend(UIComponentName) function functionName { ... }
使用规则
● 和 @Styles 不同,@Extend 仅支持定义在全局,不支持在组件内部定义。
● 和 @Styles 不同,@Extend 支持封装指定的组件的私有属性和私有事件,以及预定义相同组件的 @Extend 的方法。
// @Extend(Text)可以支持Text的私有属性fontColor @Extend(Text) function fancy () { .fontColor(Color.Red) } // superFancyText可以调用预定义的fancy @Extend(Text) function superFancyText(size:number) { .fontSize(size) .fancy() }
● 和 @Styles 不同,@Extend 装饰的方法支持参数,开发者可以在调用时传递参数,调用遵循 TS 方法传值调用。
// xxx.ets @Extend(Text) function fancy (fontSize: number) { .fontColor(Color.Red) .fontSize(fontSize) } @Entry @Component struct FancyUse { build() { Row({ space: 10 }) { Text('Fancy') .fancy(16) Text('Fancy') .fancy(24) } } }
● @Extend 装饰的方法的参数可以为 function,作为 Event 事件的句柄。
@Extend(Text) function makeMeClick(onClick: () => void) { .backgroundColor(Color.Blue) .onClick(onClick) } @Entry @Component struct FancyUse { @State label: string = 'Hello World'; onClickHandler() { this.label = 'Hello ArkUI'; } build() { Row({ space: 10 }) { Text(`${this.label}`) .makeMeClick(this.onClickHandler) } } }
● @Extend 的参数可以为状态变量,当状态变量改变时,UI 可以正常的被刷新渲染。
@Extend(Text) function fancy (fontSize: number) { .fontColor(Color.Red) .fontSize(fontSize) } @Entry @Component struct FancyUse { @State fontSizeValue: number = 20 build() { Row({ space: 10 }) { Text('Fancy') .fancy(this.fontSizeValue) .onClick(() => { this.fontSizeValue = 30 }) } } }
使用场景
以下示例声明了 3 个 Text 组件,每个 Text 组件均设置了 fontStyle、fontWeight 和 backgroundColor 样式。
@Entry @Component struct FancyUse { @State label: string = 'Hello World' build() { Row({ space: 10 }) { Text(`${this.label}`) .fontStyle(FontStyle.Italic) .fontWeight(100) .backgroundColor(Color.Blue) Text(`${this.label}`) .fontStyle(FontStyle.Italic) .fontWeight(200) .backgroundColor(Color.Pink) Text(`${this.label}`) .fontStyle(FontStyle.Italic) .fontWeight(300) .backgroundColor(Color.Orange) }.margin('20%') } }
@Extend 将样式组合复用,示例如下。
@Extend(Text) function fancyText(weightValue: number, color: Color) { .fontStyle(FontStyle.Italic) .fontWeight(weightValue) .backgroundColor(color) }
通过 @Extend 组合样式后,使得代码更加简洁,增强可读性。
@Entry @Component struct FancyUse { @State label: string = 'Hello World' build() { Row({ space: 10 }) { Text(`${this.label}`) .fancyText(100, Color.Blue) Text(`${this.label}`) .fancyText(200, Color.Pink) Text(`${this.label}`) .fancyText(300, Color.Orange) }.margin('20%') } }
审核编辑 黄宇
-
API
+关注
关注
2文章
1500浏览量
62008 -
鸿蒙
+关注
关注
57文章
2351浏览量
42847 -
OpenHarmony
+关注
关注
25文章
3722浏览量
16311
发布评论请先 登录
相关推荐
基于ArkTS语言的OpenHarmony APP应用开发:图片显示器
基于ArkTS语言的OpenHarmony APP应用开发:简易计数器
基于ArkTS语言的OpenHarmony APP应用开发:HelloOpenharmony
龙芯2K0300蜂鸟板支持OpenHarmony 4.0 Release版本操作系统
【AWTK使用经验】如何自定义combo_box下拉框样式

HarmonyOS实战开发-深度探索与打造个性化自定义组件
OpenHarmony实战开发-如何实现组件动画。

鸿蒙ArkUI实例:【自定义组件】
OpenHarmony父子组件单项同步使用:@Prop装饰器

鸿蒙OpenHarmony NAPI威廉希尔官方网站 -基础学习

评论