Harmony NEXT中,如何为ArkTS组件定义和使用自定义属性?

阅读 651
avatarAI BotBETA
在Harmony NEXT中,为ArkTS组件定义和使用自定义属性,可以通过以下步骤实现:

1. **定义自定义属性**:
   在ArkTS组件的代码中,可以通过装饰器(decorator)`@CustomProp`来定义自定义属性。装饰器后面需要跟一个属性名和一个属性类型。

import { CustomProp, Component, VNode } from '@arkui-js/arkui';

@Component
struct MyComponent {

   @CustomProp('myProp', String)
   myProp: string = '';

   build(): VNode {
       // 使用自定义属性
       console.log(this.myProp);
       return <div>Custom Property Value: {this.myProp}</div>;
   }

}


2. **使用自定义属性**:
在组件的实例化或者父组件中使用该组件时,可以通过`{}`语法或者属性绑定(例如`${}`)来传递自定义属性的值。

@Entry
@Component
struct App {

   build(): VNode {
       return <MyComponent myProp="Hello, Harmony NEXT!" />;
   }

}


通过上述步骤,您就可以在Harmony NEXT中的ArkTS组件中定义和使用自定义属性了。这些自定义属性允许您在组件之间传递数据,从而提高组件的复用性和灵活性。
1 个回答

自定义属性可通过customProperty去实现,自定义组件不支持设置自定义属性。

// xxx.ets
import { FrameNode, UIContext } from '@kit.ArkUI';

@Entry
@Component
struct CustomPropertyExample {
  build() {
    Column() {
      Text('text')
      Button('print').onClick(() => {
        const uiContext: UIContext = this.getUIContext();
        if (uiContext) {
          const node: FrameNode | null = uiContext.getFrameNodeById("Test_Column") || null;
          if (node) {
            for (let i = 1; i < 4; i++) {
              const key = 'customProperty' + i;
              const property = node.getCustomProperty(key);
              console.log(key, JSON.stringify(property));
            }
          }
        }
      })
    }
    .id('Test_Column')
    .customProperty('customProperty1', {
      'number': 10,
      'string': 'this is a string',
      'bool': true,
      'object': {
        'name': 'name',
        'value': 100
      }
    })
    .customProperty('customProperty2', {})
    .customProperty('customProperty2', undefined)
    .width('100%')
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进