• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @Component
2
3A struct decorated by **@Component** has the componentization capability and can serve as an independent component. This type of component is also called a custom component, and its UI structure is described in the **build** method. Custom components have the following features:
4
5
6- Composability: Custom components can be used with preset or other components, as well as common attributes and methods.
7
8- Reusable: Custom components can be reused by other components and used as different instances in different parent components or containers.
9- Lifecycle: Custom components provide callbacks for service logic processing throughout the lifecycle.
10- Data-driven update: The UI of custom components can be automatically updated based on the data of state variables.
11
12
13For details about componentization, see [About @Component](ts-custom-component-initialization.md).
14
15
16>  **NOTE**
17>
18>  - The **build** method must be defined for a custom component.
19>- Custom constructors are prohibited for custom components.
20
21
22The following code illustrates how to create a custom component named **MyComponent**:
23
24
25```ts
26@Component
27struct MyComponent {
28    build() {
29        Column() {
30            Text('my component')
31                .fontColor(Color.Red)
32        }.alignItems(HorizontalAlign.Center) // center align Text inside Column
33    }
34}
35```
36
37
38The **build** method of **MyComponent** is executed during initial rendering. When the component status changes, the **build** method will be executed again.
39
40
41The following code illustrates how to use **MyComponent**:
42
43
44```ts
45@Component
46struct ParentComponent {
47    build() {
48        Column() {
49            MyComponent()
50            Text('we use component')
51                .fontSize(20)
52        }
53    }
54}
55```
56
57
58**MyComponent** can be applied multiple times and reused in different components, as shown in the code below:
59
60
61```ts
62@Component
63struct ParentComponent {
64    build() {
65        Row() {
66            Column() {
67                MyComponent()
68                Text('first column')
69                    .fontSize(20)
70            }
71            Column() {
72                MyComponent()
73                Text('second column')
74                    .fontSize(20)
75            }
76        }
77    }
78
79    aboutToAppear() {
80        console.log('ParentComponent: Just created, about to become rendered first time.')
81    }
82
83    aboutToDisappear() {
84        console.log('ParentComponent: About to be removed from the UI.')
85    }
86}
87```
88