ArkTS 中提供了装饰器@State 来定义组件内部状态。
@State装饰的变量,或称为状态变量,一旦变量拥有了状态属性,就可以触发其直接绑定UI组件的刷新。当状态改变时,UI会发生对应的渲染改变。
一、@State基本语法
1、定义组件状态
在组件内部,可以通过 @State 定义多种不同类型的状态变量,且 @State 定义的数据发生改变后,会触发组件UI界面的自动更新。
但是有 2 个注意事项:
- @State 定义的变量必须设置初始值;
- @State 定义的状态只能在当前组件内部使用;
示例代码:
@Entry
@Component
struct MyPage {
// 定义一个名为message的状态
@State message: string = 'Hello World';
// 定义一个名为count的状态
@State count: number = 100;
build() {
Column() {
}
}
}
语法说明:
@State:ArkTS提供的装饰器,用来定义组件内部私有的状态;message:状态名,等同于变量名,可自定义;string:用于约束 message 状态值的类型;'Hello World':保存的状态变量值;
2、访问组件状态
在组件 build() 方法中,可以通过 this 关键字来访问 @State 定义的状态变量,实现数据的动态渲染。
示例代码:
@Entry
@Component
struct MyPage {
@State message: string = 'Hello World';
@State count: number = 100;
build() {
Column() {
Text(this.message)
Text(`${this.count}`) // 将number类型转换为string类型
}
}
}
说明:Text 组件只能渲染字符串类型的数据,如果不是字符串类型,就需要通过模板字符串的语法转换成字符串类型。
代码预览效果如下:
二、定义引用类型数据
在ArkTS中,不能按照TS中的语法方式来约束引用类型的数据。
1、定义对象类型约束
在ArkTS中,需要通过class的语法来定义对象的类型:
class UserItem {
id: string;
username: string;
age: number;
constructor(id: string, username: string, age: number) {
this.id = id;
this.username = username;
this.age = age;
}
}
2、定义引用类型初始数据
在ArkTS中,需要通过 new class 的方式来定义一个对象类型的数据:
class UserItem {
id: string;
username: string;
age: number;
constructor(id: string, username: string, age: number) {
this.id = id;
this.username = username;
this.age = age;
}
}
@Entry
@Component
struct MyPage {
// 定义对象
@State zhangsan: UserItem = new UserItem('1', '张三', 20)
// 定义数组
@State students: UserItem[] = [
new UserItem('1', '李四', 20),
new UserItem('2', '王五', 22),
]
build() {
Column() {
}
}
}
3、渲染引用类型的数据
@Entry
@Component
struct MyPage {
@State zhangsan: UserItem = new UserItem('1', '张三', 20)
@State students: UserItem[] = [
new UserItem('1', '李四', 20),
new UserItem('2', '王五', 22),
]
build() {
Column() {
// 渲染整个对象
Text(`${JSON.stringify(this.zhangsan)}`)
// 渲染整个数组
Text(`${JSON.stringify(this.students)}`)
// 渲染对象的属性
Text(`姓名:${this.student.username}`)
Text(`年龄:${this.student.age}`)
}
}
}
说明:由于 Text 只能渲染字符串,因此需要通过 JSON.stringify() 方法讲引用类型的数据转换成字符串类型。
代码预览效果如下: