【中秋国庆不断更】openharmony定义扩展组件样式:@extend装饰器
在前文的示例中,可以使用@styles用于样式的扩展,在@styles的基础上,我们提供了@extend,用于扩展原生组件样式。
说明: 从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%')
}
}
发表评论