State 管理状态
- 支持
string
number
类型的状态管理
@Entry
@Component
struct StatePage {
@State name: string = '马云'
@State age: number = 55
build() {
Column({space: 20}){
Text(`姓名: ${this.name} _年龄: ${this.age}`)
.fontSize(30)
.onClick((e)=> {
this.age++
})
}.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
2 支持class
类型的状态管理, class的实例对象的属性发生变化, 页面也会发生变化
class Person {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
@Entry
@Component
struct StatePage2 {
@State p: Person = new Person('马云', 77)
build() {
Column({space: 20}){
Text(`姓名: ${this.p.name} _年龄: ${this.p.age}`)
.fontSize(30)
.onClick((e)=> {
this.p.age++
})
}.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
注意: 对class嵌套的class实例对象的属性无法用State 做管理状态
这种情况, this.p.friend.age的值变化, 页面不会跟随变化
friend?: Person
表示传入的参数可选 (可传可不传)
class Person {
name: string
age: number
friend: Person
constructor(name: string, age: number, friend?: Person) {
this.name = name
this.age = age
this.friend = friend
}
}
@Entry
@Component
struct StatePage2 {
@State p: Person = new Person('马云', 77, new Person('刘强东',52, null))
build() {
Column({space: 20}){
Text(`姓名: ${this.p.friend.name} _年龄: ${this.p.friend.age}`)
.fontSize(30)
.onClick((e)=> {
this.p.friend.age++
})
}.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
数组使用状态管理时, 删除元素,添加元素都会触发, 修改数组中某个对象的某个属性, 不会触发
@prop和@Link
@Provide和@Comsume
爷爷组件和孙子组件之间的数据传递
爷爷写@Provide
@Provide totalTask: number
孙子写@Comsume
@Comsume totalTask: number
totalTask属性数据就会自动进行传递
@Observed和@ObjectLink 需要配合使用
@Observed //修饰对象作为嵌套对象时,修改对象属性, 能够触发数据同步
class Person {
name: string
age: number
gf: Person
constructor(name: string,age: number, gf?: Person) {
this.name = name
this.age = age
this.gf = gf
}
}
@Entry
@Component
struct ObservedAndObjectLink {
@State dava: Person = new Person("davai",18,new Person("luxi", 18))
build() {
Column({space: 20}){
// Child(this.dava)
Text( `name: ${this.dava.name} age: ${this.dava.age}`)
.fontSize(30)
.onClick(e => {
this.dava.age++;
})
Child({p: this.dava.gf})
}.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Component
struct Child {
@ObjectLink p: Person //申明对象需要进行双向数据绑定
build(){
Text( `name: ${this.p.name} age: ${this.p.age}`)
.fontSize(30)
.onClick(e => {
this.p.age++;
})
}
}
函数作为参数传递
传递时, 如果函数中需要访问当前方法中的this
, 则需要在参数传递时进行bind
操作
例如下面 Child({changeFinishTask: this.resetfinishTask.bind(this)})
, 这样方法中的this才能访问到tasks, totalTask 等属性
@Component
struct TaskList {
@Link tasks: Task[]
@Link totalTask: number
@Link finishTask: number
build() {
Child({changeFinishTask: this.resetfinishTask.bind(this)})
}
resetfinishTask() {
this.finishTask = this.tasks.filter(item => item.finish).length
}
}
@Component
struct Child {
changeFinishTask: () => void
build(){}
}