1# ComponentContent
2
3ComponentContent表示组件内容的实体封装,其对象支持在非UI组件中创建与传递,便于开发者对弹窗类组件进行解耦封装。ComponentContent底层使用了BuilderNode,相关使用规格参考[BuilderNode](js-apis-arkui-builderNode.md)。
4
5> **说明:**
6>
7> 本模块从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>
9> 当前不支持在预览器中使用ComponentContent。
10
11
12## 导入模块
13
14```ts
15import { ComponentContent } from '@kit.ArkUI';
16```
17
18## ComponentContent
19
20### constructor
21
22constructor(uiContext: UIContext, builder: WrappedBuilder\<[]>)
23
24ComponentContent的构造函数。
25
26**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
27
28**系统能力:** SystemCapability.ArkUI.ArkUI.Full
29
30**参数:**
31
32| 参数名    | 类型                                      | 必填 | 说明                               |
33| --------- | ----------------------------------------- | ---- | ---------------------------------- |
34| uiContext | [UIContext](./js-apis-arkui-UIContext.md) | 是   | 创建对应节点时候所需要的UI上下文。 |
35| builder  | [WrappedBuilder\<[]>](../../quick-start/arkts-wrapBuilder.md) | 是   |   封装不带参builder函数的WrappedBuilder对象。 |
36
37### constructor
38
39constructor(uiContext: UIContext, builder: WrappedBuilder\<[T]>, args: T)
40
41ComponentContent的构造函数。
42
43**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
44
45**系统能力:** SystemCapability.ArkUI.ArkUI.Full
46
47**参数:**
48
49| 参数名    | 类型                                      | 必填 | 说明                               |
50| --------- | ----------------------------------------- | ---- | ---------------------------------- |
51| uiContext | [UIContext](./js-apis-arkui-UIContext.md) | 是   | 创建对应节点时候所需要的UI上下文。 |
52| builder  | [WrappedBuilder\<[T]>](../../quick-start/arkts-wrapBuilder.md) | 是   |   封装带参builder函数的WrappedBuilder对象。 |
53| args     |     T     |   是   |   WrappedBuilder对象封装的builder函数的参数。 |
54
55### constructor
56
57  constructor(uiContext: UIContext, builder: WrappedBuilder\<[T]>, args: T, options: BuildOptions)
58
59ComponentContent的构造函数。
60
61**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
62
63**系统能力:** SystemCapability.ArkUI.ArkUI.Full
64
65**参数:**
66
67| 参数名    | 类型                                      | 必填 | 说明                               |
68| --------- | ----------------------------------------- | ---- | ---------------------------------- |
69| uiContext | [UIContext](./js-apis-arkui-UIContext.md) | 是   | 创建对应节点时候所需要的UI上下文。 |
70| builder  | [WrappedBuilder\<[T]>](../../quick-start/arkts-wrapBuilder.md) | 是   |   封装带参builder函数的WrappedBuilder对象。 |
71| args     |     T     |   是   |   WrappedBuilder对象封装的builder函数的参数。 |
72| options | [BuildOptions](./js-apis-arkui-builderNode.md#buildoptions12)                                                    | 是   |  build的配置参数,判断是否支持@Builder中嵌套@Builder的行为。                                         |
73
74**示例:**
75``` ts
76import { ComponentContent, NodeContent, typeNode } from "@kit.ArkUI"
77
78interface ParamsInterface {
79  text: string;
80  func: Function;
81}
82
83@Builder
84function buildTextWithFunc(fun: Function) {
85  Text(fun())
86    .fontSize(50)
87    .fontWeight(FontWeight.Bold)
88    .margin({ bottom: 36 })
89}
90
91@Builder
92function buildText(params: ParamsInterface) {
93  Column() {
94    Text(params.text)
95      .fontSize(50)
96      .fontWeight(FontWeight.Bold)
97      .margin({ bottom: 36 })
98    buildTextWithFunc(params.func)
99  }
100}
101
102@Entry
103@Component
104struct Index {
105  @State message: string = "HELLO"
106  private content: NodeContent = new NodeContent();
107
108  build() {
109    Row() {
110      Column() {
111        Button('addComponentContent')
112          .onClick(() => {
113            let column = typeNode.createNode(this.getUIContext(), "Column");
114            column.initialize();
115            column.addComponentContent(new ComponentContent<ParamsInterface>(this.getUIContext(),
116              wrapBuilder<[ParamsInterface]>(buildText), {
117                text: this.message, func: () => {
118                  return "FUNCTION"
119                }
120              }, { nestingBuilderSupported: true }))
121            this.content.addFrameNode(column);
122          })
123        ContentSlot(this.content)
124      }
125      .id("column")
126      .width('100%')
127      .height('100%')
128    }
129    .height('100%')
130  }
131}
132
133```
134
135### update
136
137update(args: T): void
138
139用于更新WrappedBuilder对象封装的builder函数参数,与constructor传入的参数类型保持一致。
140
141**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
142
143**系统能力:** SystemCapability.ArkUI.ArkUI.Full
144
145**参数:**
146
147| 参数名 | 类型 | 必填 | 说明                                                         |
148| ------ | ---- | ---- | ------------------------------------------------------------ |
149| args   | T    | 是   | 用于更新WrappedBuilder对象封装的builder函数参数,与constructor传入的参数类型保持一致。 |
150
151**示例:**
152
153```ts
154import { ComponentContent } from "@kit.ArkUI";
155
156class Params {
157  text: string = ""
158  constructor(text: string) {
159    this.text = text;
160  }
161}
162
163@Builder
164function buildText(params: Params) {
165  Column() {
166    Text(params.text)
167      .fontSize(50)
168      .fontWeight(FontWeight.Bold)
169      .margin({bottom: 36})
170  }.backgroundColor('#FFF0F0F0')
171}
172
173@Entry
174@Component
175struct Index {
176  @State message: string = "hello"
177
178  build() {
179    Row() {
180      Column() {
181        Button("click me")
182            .onClick(() => {
183                let uiContext = this.getUIContext();
184                let promptAction = uiContext.getPromptAction();
185                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
186                promptAction.openCustomDialog(contentNode);
187
188                setTimeout(() => {
189                  contentNode.update(new Params("new message"));
190                }, 2000);    //2秒后自动更新弹窗内容文本
191            })
192      }
193      .width('100%')
194      .height('100%')
195    }
196    .height('100%')
197  }
198}
199```
200
201### reuse
202
203reuse(param?: Object): void
204
205传递reuse事件到ComponentContent中的自定义组件。
206
207**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
208
209**系统能力:** SystemCapability.ArkUI.ArkUI.Full
210
211**参数:**
212
213| 参数名 | 类型   | 必填 | 说明                                                                     |
214| ------ | ------ | ---- | ------------------------------------------------------------------------ |
215| param  | Object | 否   | 用于复用WrappedBuilder对象封装的builder函数参数,与constructor传入的参数类型保持一致。 |
216
217### recycle
218
219recycle(): void
220
221传递recycle事件到ComponentContent中的自定义组件。
222
223**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
224
225**系统能力:** SystemCapability.ArkUI.ArkUI.Full
226
227```ts
228import { ComponentContent } from '@kit.ArkUI';
229
230class Params {
231  text: string = ""
232
233  constructor(text: string) {
234    this.text = text;
235  }
236}
237
238@Builder
239function buildText(params: Params) {
240  ReusableChildComponent2({ text: params.text });
241}
242
243@Component
244struct ReusableChildComponent2 {
245  @Prop text: string = "false";
246
247  aboutToReuse(params: Record<string, object>) {
248    console.log("ReusableChildComponent2 Reusable " + JSON.stringify(params));
249  }
250
251  aboutToRecycle(): void {
252    console.log("ReusableChildComponent2 aboutToRecycle " + this.text);
253  }
254
255  build() {
256    Column() {
257      Text(this.text)
258        .fontSize(50)
259        .fontWeight(FontWeight.Bold)
260        .margin({ bottom: 36 })
261    }.backgroundColor('#FFF0F0F0')
262  }
263}
264
265@Entry
266@Component
267struct Index {
268  @State message: string = "hello"
269
270  build() {
271    Row() {
272      Column() {
273        Button("click me")
274          .onClick(() => {
275            let uiContext = this.getUIContext();
276            let promptAction = uiContext.getPromptAction();
277            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
278            promptAction.openCustomDialog(contentNode);
279
280            setTimeout(() => {
281              contentNode.reuse(new Params("new message"));
282              contentNode.recycle();
283            }, 2000); //2秒后自动更新弹窗内容文本
284          })
285      }
286      .width('100%')
287      .height('100%')
288    }
289    .height('100%')
290  }
291}
292```
293
294### dispose
295
296dispose(): void
297
298立即释放当前ComponentContent,即ComponentContent对象与后端实体节点解除引用关系。
299
300**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
301
302**系统能力:** SystemCapability.ArkUI.ArkUI.Full
303
304**示例:**
305
306```ts
307import { BusinessError } from '@kit.BasicServicesKit';
308import { ComponentContent } from '@kit.ArkUI';
309
310class Params {
311  text: string = ""
312  constructor(text: string) {
313    this.text = text;
314  }
315}
316
317@Builder
318function buildText(params: Params) {
319  Column() {
320    Text(params.text)
321      .fontSize(50)
322      .fontWeight(FontWeight.Bold)
323      .margin({bottom: 36})
324  }.backgroundColor('#FFF0F0F0')
325}
326
327@Entry
328@Component
329struct Index {
330  @State message: string = "hello"
331
332  build() {
333    Row() {
334      Column() {
335        Button("click me")
336            .onClick(() => {
337                let uiContext = this.getUIContext();
338                let promptAction = uiContext.getPromptAction();
339                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
340                promptAction.openCustomDialog(contentNode);
341
342                setTimeout(() => {
343                  promptAction.closeCustomDialog(contentNode)
344                    .then(() => {
345                      console.info('customdialog closed.')
346                      if (contentNode !== null) {
347                        contentNode.dispose();   //释放contentNode
348                      }
349                    }).catch((error: BusinessError) => {
350                      let message = (error as BusinessError).message;
351                      let code = (error as BusinessError).code;
352                      console.error(`closeCustomDialog args error code is ${code}, message is ${message}`);
353                    })
354                }, 2000);     //2秒后自动关闭
355            })
356      }
357      .width('100%')
358      .height('100%')
359    }
360    .height('100%')
361  }
362}
363```
364
365
366### updateConfiguration
367
368updateConfiguration(): void
369
370传递[系统环境变化](../apis-ability-kit/js-apis-app-ability-configuration.md)事件,触发节点的全量更新。
371
372**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
373
374**系统能力:** SystemCapability.ArkUI.ArkUI.Full
375
376> **说明:**
377>
378> updateConfiguration接口功能为通知对象更新,更新所使用的系统环境由当前的系统环境变化。
379
380**示例:**
381```ts
382import { NodeController, FrameNode, ComponentContent, typeNode } from '@kit.ArkUI';
383import { AbilityConstant, Configuration, EnvironmentCallback } from '@kit.AbilityKit';
384
385@Builder
386function buildText() {
387  Column() {
388    Text('hello')
389      .width(50)
390      .height(50)
391      .fontColor($r(`app.color.text_color`))
392  }.backgroundColor($r(`app.color.start_window_background`))
393}
394
395const componentContentMap: Array<ComponentContent<[Object]>> = new Array();
396
397class MyNodeController extends NodeController {
398  private rootNode: FrameNode | null = null;
399
400  makeNode(uiContext: UIContext): FrameNode | null {
401    return this.rootNode;
402  }
403
404  createNode(context: UIContext) {
405    this.rootNode = new FrameNode(context);
406    let component = new ComponentContent<Object>(context, wrapBuilder(buildText));
407    componentContentMap.push(component);
408    this.rootNode.addComponentContent(component);
409  }
410
411  deleteNode() {
412    let node = componentContentMap.pop();
413    this.rootNode?.dispose();
414    node?.dispose();
415  }
416}
417
418function updateColorMode() {
419  componentContentMap.forEach((value, index) => {
420    value.updateConfiguration();
421  })
422}
423
424@Entry
425@Component
426struct FrameNodeTypeTest {
427  private myNodeController: MyNodeController = new MyNodeController();
428
429  aboutToAppear(): void {
430    let environmentCallback: EnvironmentCallback = {
431      onMemoryLevel: (level: AbilityConstant.MemoryLevel): void => {
432        console.log('onMemoryLevel');
433      },
434      onConfigurationUpdated: (config: Configuration): void => {
435        console.log('onConfigurationUpdated ' + JSON.stringify(config));
436        updateColorMode();
437      }
438    }
439    // 注册监听回调
440    this.getUIContext().getHostContext()?.getApplicationContext().on('environment', environmentCallback);
441    this.myNodeController.createNode(this.getUIContext());
442  }
443
444  aboutToDisappear(): void {
445    //移除map中的引用,并将自定义节点释放
446    this.myNodeController.deleteNode();
447  }
448
449  build() {
450    Row() {
451      NodeContainer(this.myNodeController);
452    }
453  }
454}
455```
456