如果每个组件的款式都须要独自设置,在开发过程中会呈现大量代码在进行反复款式设置,尽管能够复制粘贴,但为了代码简洁性和后续不便保护,咱们推出了能够提炼公共款式进行复用的装璜器 @Styles。

@Styles 装璜器能够将多条款式设置提炼成一个办法,间接在组件申明的地位调用。通过 @Styles 装璜器能够疾速定义并复用自定义款式。用于疾速定义并复用自定义款式。

阐明:

从 API version 9 开始,该装璜器反对在 ArkTS 卡片中应用。

装璜器应用阐明

● 以后 @Styles 仅反对通用属性和通用事件。

● @Styles 办法不反对参数,反例如下。

// 反例: @Styles不反对参数@Styles function globalFancy (value: number) {  .width(value)}

● @Styles 能够定义在组件内或全局,在全局定义时需在办法名后面增加 function 关键字,组件内定义时则不须要增加 function 关键字。

// 全局@Styles function functionName() { ... }// 在组件内@Componentstruct FancyUse {  @Styles fancy() {    .height(100)  }}

// 全局
@Styles function functionName() { ... }

// 在组件内@Componentstruct FancyUse {  @Styles fancy() {    .height(100)  }}

● 定义在组件内的 @Styles 能够通过 this 拜访组件的常量和状态变量,并能够在 @Styles 里通过事件来扭转状态变量的值,示例如下:

@Componentstruct FancyUse {  @State heightValue: number = 100  @Styles fancy() {    .height(this.heightValue)    .backgroundColor(Color.Yellow)    .onClick(() => {      this.heightValue = 200    })  }}

● 组件内 @Styles 的优先级高于全局 @Styles。 框架优先找以后组件内的 @Styles,如果找不到,则会全局查找。

应用场景

以下示例中演示了组件内 @Styles 和全局 @Styles 的用法。

// 定义在全局的@Styles封装的款式@Styles function globalFancy  () {  .width(150)  .height(100)  .backgroundColor(Color.Pink)}@Entry@Componentstruct FancyUse {  @State heightValue: number = 100  // 定义在组件内的@Styles封装的款式  @Styles fancy() {    .width(200)    .height(this.heightValue)    .backgroundColor(Color.Yellow)    .onClick(() => {      this.heightValue = 200    })  }  build() {    Column({ space: 10 }) {      // 应用全局的@Styles封装的款式      Text('FancyA')        .globalFancy ()        .fontSize(30)      // 应用组件内的@Styles封装的款式      Text('FancyB')        .fancy()        .fontSize(30)    }  }}