赞
踩
根据业务需求,将已有组件进行组合,封装成新的组件,可以在工程中多次调用,从而提高代码的复用性与可读性
自定义组件必须使用struct定义,并且被Component装饰器修饰
自定义组件的特点:
将入口组件@Entry去掉就可以在其他自定义组件中的build()函数中多次创建,实现自定义组件的重用
注意:如果在另外的文件中引用该自定义组件,需要使用export关键字导出,并在使用的页面import该自定义组件
- @Component
- export struct HelloPage {
- @State message: string = 'Hello World'
-
- build() {
- Row() {
- Column() {
- Text(this.message)
- .fontSize(40)
- .fontWeight(FontWeight.Bold)
- .onClick(() => {
- this.message = "Hello Harmonyos"
- })
- }
- .width('100%')
- }
- .height('100%')
- }
- }

- import { HelloPage } from './HelloPage'
-
- @Entry
- @Component
- struct TestPage {
- msg: string = 'Hello World'
-
- build() {
- Row() {
- Column() {
- HelloPage({ message: this.msg })
- }
- .width('100%')
- }
- .height('100%')
- }
- }

自定义组件中可以实现其他成员函数,这些成员函数的访问是私有的,不支持静态函数。
也可以包含其他成员变量,也是私有的,不支持静态成员变量。
- @Component
- export struct HelloPage {
- @State message: string = 'Hello World'
- private MSG_STRING: string = 'Harmonyos'
-
- build() {
- Row() {
- Column() {
- Text(this.message)
- .fontSize(40)
- .fontWeight(FontWeight.Bold)
- .onClick(() => {
- this.setMsg(this.MSG_STRING)
- this.message = this.getMsg()
- })
- }
- .width('100%')
- }
- .height('100%')
- }
-
- setMsg(msg: string) {
- this.message = msg
- }
-
- getMsg(): string {
- return 'hello:' + this.message
- }
- }

-
- //自定义组件,定义属性
- @Component
- export struct HelloPage {
- @State message: string = 'Hello World'
- private MSG_STRING: string = 'Harmonyos'
-
- ……
- }
-
- //调用处调用
- HelloPage({ message: this.msg, MSG_STRING: '世界' })
可以设置通用样式,通过“.”链式调用的形式设置
- HelloPage({ message: this.msg, MSG_STRING:this.getStr() })
- .width(100)
- .backgroundColor(Color.Red)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。