• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 挂载卸载事件
2
3挂载卸载事件指组件从组件树上挂载、卸载时触发的事件。
4
5> **说明:**
6>
7> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8
9## onAttach<sup>12+</sup>
10
11onAttach(callback: Callback\<void>): T
12
13组件挂载至组件树时触发此回调。
14
15> **说明:**
16>
17> 回调的调用时机一定在组件布局渲染之前。
18>
19> 不允许在回调中对组件树进行变更,例如启动动画,或是使用if-else变更组件树结构。
20
21**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
22
23**系统能力:** SystemCapability.ArkUI.ArkUI.Full
24
25**返回值:**
26
27| 类型 | 说明 |
28| -------- | -------- |
29| T | 返回当前组件。 |
30
31
32## onDetach<sup>12+</sup>
33
34onDetach(callback: Callback\<void>): T
35
36组件从组件树卸载时触发此回调。
37
38**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
39
40**系统能力:** SystemCapability.ArkUI.ArkUI.Full
41
42**返回值:**
43
44| 类型 | 说明 |
45| -------- | -------- |
46| T | 返回当前组件。 |
47
48## onAppear
49
50onAppear(event: () => void): T
51
52组件挂载显示后触发此回调。
53
54> **说明:**
55>
56> 回调的调用时机有可能发生在组件布局渲染后。
57
58**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
59
60**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
61
62**系统能力:** SystemCapability.ArkUI.ArkUI.Full
63
64**返回值:**
65
66| 类型 | 说明 |
67| -------- | -------- |
68| T | 返回当前组件。 |
69
70
71## onDisAppear
72
73onDisAppear(event: () => void): T
74
75组件卸载消失时触发此回调。
76
77**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
78
79**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
80
81**系统能力:** SystemCapability.ArkUI.ArkUI.Full
82
83**返回值:**
84
85| 类型 | 说明 |
86| -------- | -------- |
87| T | 返回当前组件。 |
88
89
90## 示例
91
92```ts
93// xxx.ets
94import { promptAction } from '@kit.ArkUI'
95
96@Entry
97@Component
98struct AppearExample {
99  @State isShow: boolean = true
100  @State changeAppear: string = '点我卸载挂载组件'
101  private myText: string = 'Text for onAppear'
102
103  build() {
104    Column() {
105      Button(this.changeAppear)
106        .onClick(() => {
107          this.isShow = !this.isShow
108        }).margin(15)
109      if (this.isShow) {
110        Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
111          .onAttach(() => {
112            promptAction.showToast({
113              message: 'The text is shown',
114              duration: 2000,
115              bottom: 500
116            })
117          })
118          .onDetach(() => {
119            promptAction.showToast({
120              message: 'The text is hidden',
121              duration: 2000,
122              bottom: 500
123            })
124          })
125      }
126    }.padding(30).width('100%')
127  }
128}
129```
130
131![zh-cn_image_0000001219864151](figures/zh-cn_image_0000001219864151.gif)
132