HarmonyOS 怎么自定义装饰器

怎么自定义装饰器,有没有简单的demo

HarmonyOS
2024-12-24 16:27:40
1173浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
superinsect

ArkTS支持TS5.0之前的TS装饰器语法。关于装饰器的定义和运行时行为,可以参考TS官方文档:https://www.typescriptlang.org/docs/handbook/decorators.html

注意,如果在ets文件中定义装饰器,则需要同时满足ArkTS的语法规则,比如不能使用any等。以下是简单示例:

// 类装饰器
function decorateKlass(target: ESObject) {
  console.log("decorateKlass")
}

@decorateKlass
class Person {
  age: number = 12
}


// 方法装饰器
export function MyDescriptor(target: Object, key: string, descriptor: PropertyDescriptor) {
  const originalMethod: Function = descriptor.value
  descriptor.value = (...args: Object[]) => {
    console.log(`Calling ${target.constructor.name} method ${key} with argument: ${args}`)
    const result: Object = originalMethod(...args)
    console.log(`Method ${key} returned: ${result}`)
    return result
  }
  return descriptor
}

@Entry
@Component
struct DecoratorDemo {
  @State message: string = 'Hello World';

  aboutToAppear() {
    this.demo()
  }

  build() {
    Flex() {
    }
    .backgroundColor(Color.Green)
    .constraintSize({
      minWidth: 100,
      maxWidth: 200,
      minHeight: 0,
      maxHeight: 200
    })
    .height('100%')
  }

  @MyDescriptor
  demo() {
    let person = new Person();
    return person.age
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
分享
微博
QQ
微信
回复
2024-12-24 18:20:23
相关问题
是否支持自定义装饰
2914浏览 • 1回复 待解决
HarmonyOS 是否支持自定义装饰
1073浏览 • 1回复 待解决
ArkTS是否支持自定义装饰
3629浏览 • 1回复 待解决
自定义装饰的使用问题
1544浏览 • 1回复 待解决
HarmonyOS ArkTS 如何实现自定义装饰
850浏览 • 1回复 待解决
HarmonyOS 自定义装饰的this指向问题
904浏览 • 1回复 待解决
HarmonyOS 能否自定义自己的装饰
875浏览 • 2回复 待解决
HarmonyOS 自定义装饰不能作用于ets
1496浏览 • 1回复 待解决
HarmonyOS 自定义视频控制
913浏览 • 1回复 待解决