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该示例通过按钮控制组件的卸载和挂载,触发onAttach和onDetach事件。
93
94```ts
95// xxx.ets
96import { promptAction } from '@kit.ArkUI'
97
98@Entry
99@Component
100struct AppearExample {
101  @State isShow: boolean = true
102  @State changeAppear: string = '点我卸载挂载组件'
103  private myText: string = 'Text for onAppear'
104
105  build() {
106    Column() {
107      Button(this.changeAppear)
108        .onClick(() => {
109          this.isShow = !this.isShow
110        }).margin(15)
111      if (this.isShow) {
112        Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
113          .onAttach(() => {
114            promptAction.showToast({
115              message: 'The text is shown',
116              duration: 2000,
117              bottom: 500
118            })
119          })
120          .onDetach(() => {
121            promptAction.showToast({
122              message: 'The text is hidden',
123              duration: 2000,
124              bottom: 500
125            })
126          })
127      }
128    }.padding(30).width('100%')
129  }
130}
131```
132
133![zh-cn_image_0000001219864151](figures/zh-cn_image_0000001219864151.gif)
134