网站后台管理系统制作教程,商务网站建设与管理,vi画册设计,网站建设先做后定义扩展组件样式#xff1a;Extend装饰器
在前文的示例中#xff0c;可以使用Styles用于样式的重用#xff0c;在Styles的基础上#xff0c;我们提供了Extend#xff0c;用于扩展原生组件样式。 说明 从API version 9开始#xff0c;该装饰器支持在ArkTS卡片中使用。 从…定义扩展组件样式Extend装饰器
在前文的示例中可以使用Styles用于样式的重用在Styles的基础上我们提供了Extend用于扩展原生组件样式。 说明 从API version 9开始该装饰器支持在ArkTS卡片中使用。 从API version 11开始该装饰器支持在元服务中使用。 装饰器使用说明
语法
Extend(UIComponentName) function functionName { ... }
使用规则
和Styles不同Extend仅支持在全局定义不支持在组件内部定义。
说明
只能在当前文件内使用不支持export
如果想实现export功能推荐使用AttributeModifier 和Styles不同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 20build() {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 Worldbuild() {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 Worldbuild() {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%)}
}