#鸿蒙通关秘籍#如何在ArkTS中定义和使用@Styles实现组件样式的复用?

HarmonyOS
2024-11-26 16:05:10
1543浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
逍遥吃瓜

使用@Styles装饰器可以为组件定义可复用的样式,其主要用于封装公共的UI属性和事件。定义和使用的方法如下:

  1. 全局定义@Styles

    @Styles
    function globalStyle() {
      .width('100%')
      .height(100)
      .padding(10)
      .backgroundColor(Color.Green)
    }
    
    @Entry
    @Component
    struct Parent {
      build() {
        Text('示例文本').globalStyle()
      }
    }
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
  2. 组件内部定义@Styles

    @Entry
    @Component
    struct Demo {
      @Styles functionName() {
        .height(100)
      }
    
      build() {
        Image().functionName()
      }
    }
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.

这种方式可以将常用的样式封装成函数,并在多个组件中灵活应用,进一步增强了代码的模块化和整体性。


分享
微博
QQ
微信
回复
2024-11-26 17:05:08


相关问题
如何在 ArkTS 定义使用接口?
1011浏览 • 0回复 待解决