@Styles装饰器:定义组件重用样式
如果每个组件的样式都需要单独设置,在开发过程中会出现大量代码在进行重复样式设置,虽然可以复制粘贴,但为了代码简洁性和后续方便维护,我们推出了可以提炼公共样式进行复用的装饰器@Styles。
@Styles装饰器可以将多条样式设置提炼成一个方法,直接在组件声明的位置调用。通过@Styles装饰器可以快速定义并复用自定义样式。用于快速定义并复用自定义样式。
装饰器使用说明
-
@Styles方法不支持参数,反例如下。
// Styles注解表注的方法不允许携带参数 如果携带编译时会提示错误 /** * [Compile Result] @Styles can't have parameters. * [Compile Result] Unexpected token (Note that you need plugins to import files that are not JavaScript) * [Compile Result] Compile error occurred. Fix it based on the above message. */ @Styles function globalFancy (value: number) { .width(value) }
-
@Styles可以定义在组件内或全局,在全局定义时需在方法名前面添加function关键字,组件内定义时则不需要添加function关键字。
// 全局 @Styles function functionName() { ... } // 在组件内 @Component struct FancyUse { @Styles fancy() { .height(100) } } ts
-
定义在组件内的@Styles可以通过this访问组件的常量和状态变量,并可以在@Styles里通过事件来改变状态变量的值,示例如下:
@Component struct FancyUse { @State heightValue: number = 100 @Styles fancy() { .height(this.heightValue) .backgroundColor(Color.Yellow) .onClick(() => { this.heightValue = 2 00 }) } }
-
组件内@Styles的优先级高于全局@Styles。 框架优先找当前组件内的@Styles,如果找不到,则会全局查找。
使用场景
以下示例中演示了组件内@Styles和全局@Styles的用法。
@Entry
@Component
struct StylesDecoratorDome {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.stylesTest() // 调用全局样式
.insideStyle() // 调用组件内样式
}
.width('100%')
}
.height('100%')
}
// 组件内定义样式 宽度100% 背景为白色
@Styles insideStyle(){
.width("100%")
.backgroundColor(Color.White)
}
}
// Styles注解表注的方法不允许携带参数 如果携带编译时会提示错误
/**
* [Compile Result] @Styles can't have parameters.
* [Compile Result] Unexpected token (Note that you need plugins to import files that are not JavaScript)
* [Compile Result] Compile error occurred. Fix it based on the above message.
*
* 全局定义样式 宽度50vp 背景颜色为黄色
*/
@Styles function stylesTest() {
.width("50vp")
.backgroundColor(Color.Yellow)
}
运行结果: