目录
概要
在前文我们使用了@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组合样式后,使得代码更加简洁,增强可读性。