1# 自定义属性设置
2
3当开发者希望在组件上设置自定义的属性时,可以使用自定义属性设置功能,在组件上设置自定义的属性。而这些自定义属性可以在其对应的FrameNode上获取,从而实现更自由的组件管理。
4
5>  **说明:**
6>
7>  从API Version 12开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8
9## customProperty
10
11customProperty(name: string, value: Optional\<Object>)
12
13设置组件的自定义属性。[自定义组件](../../../quick-start/arkts-create-custom-components.md#创建自定义组件)不支持设置自定义属性。
14
15**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
16
17**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
18
19**系统能力:** SystemCapability.ArkUI.ArkUI.Full
20
21**参数:**
22
23| 参数名 | 类型                                                 | 必填 | 说明                                                         |
24| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
25| name  | string | 是   | 自定义属性的名称。 |
26| value  | Optional\<Object> | 是   | 自定义属性的值。 |
27
28
29## Optional<sup>12+</sup>
30
31Optional\<T>
32
33定义可选类型,其值可以是undefined。
34
35**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
36
37**系统能力:** SystemCapability.ArkUI.ArkUI.Full
38
39**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
40
41## 示例
42
43在Column组件上设置自定义属性,并在其对应的FrameNode上获取所设置的自定义属性。
44
45```ts
46// xxx.ets
47import { FrameNode, UIContext } from '@kit.ArkUI';
48
49@Entry
50@Component
51struct CustomPropertyExample {
52  build() {
53    Column() {
54      Text('text')
55      Button('print').onClick(() => {
56        const uiContext: UIContext = this.getUIContext();
57        if (uiContext) {
58          const node: FrameNode | null = uiContext.getFrameNodeById("Test_Column") || null;
59          if (node) {
60            for (let i = 1; i < 4; i++) {
61              const key = 'customProperty' + i;
62              const property = node.getCustomProperty(key);
63              console.log(key, JSON.stringify(property));
64            }
65          }
66        }
67      })
68    }
69    .id('Test_Column')
70    .customProperty('customProperty1', {
71      'number': 10,
72      'string': 'this is a string',
73      'bool': true,
74      'object': {
75        'name': 'name',
76        'value': 100
77      }
78    })
79    .customProperty('customProperty2', {})
80    .customProperty('customProperty2', undefined)
81    .width('100%')
82    .height('100%')
83  }
84}
85```
86