目录
组件编程在使用过程中有很多技巧,在这里分享样式复用技巧和UI结构复用技巧。
样式复用
我们观察下面的代码,在代码中很多重复行的代码,如:
Image 的 .width(30).height(30) 是重复的 Button的 .fontSize(25).width(150).height(65).backgroundColor(Color.Green)是重复的 Text 的 .fontSize(20).fontColor(Color.White).fontWeight(500) 是重复的
@Entry
@Component
struct customStyle {
@State isOn: boolean = false;
@State isDel: boolean = false;
build() {
Column({ space: 10 }) {
Button({ type: ButtonType.Capsule, stateEffect: true }) {
Row({ space: 10 }) {
Image($r('app.media.icon_new_folder'))
.width(30)
.height(30)
Text('新建文件')
.fontSize(20)
.fontColor(Color.White)
.fontWeight(500)
}
}
.fontSize(25)
.width(150)
.height(65)
.backgroundColor(Color.Green)
.onClick(() => {
console.log('我准备开始建立文件夹');
})
Button({ type: ButtonType.Capsule, stateEffect: true }) {
Row({ space: 10 }) {
Image($r('app.media.icon_new_folder'))
.width(30)
.height(30)
Text('新建文件')
.fontSize(20)
.fontColor(Color.White)
.fontWeight(500)
}
}
.fontSize(25)
.width(150)
.height(65)
.backgroundColor(Color.Green)
.onClick(() => {
console.log('我准备开始建立文件夹');
})
}
.width('100%')
.height("100%")
.justifyContent(FlexAlign.Center)
}
}
@Extend(Image) function consumeImgStyle() {
.width(30)
.height(30)
}
@Extend(Button) function consumeButtonStyle() {
.fontSize(25)
.width(150)
.height(65)
}
@Extend(Text) function consumeBTextStyle() {
.fontSize(20)
.fontColor(Color.White)
.fontWeight(500)
}
当多个组件具有相同的样式时,若每个组件都单独设置,将会有大量的重复代码。为避免重复代码,开发者可使用@Styles或者@Extend装饰器将多条样式设置提炼成一个方法,然后直接在各组件声明的位置进行调用,这样就能完成样式的复用。
@Styles方法
@Styles方法可定义在组件内或者全局。
- 1. 组件内定义的@Styles方法只能在当前组件中使用,全局的@Styles方法目前只允许在当前的.ets文件中使用
- 2. 组件内定义@Styles方法时不需要使用function关键字,全局的@Styles方法需要使用functi