前言
随着鸿蒙技术的普及,我们是时候学习鸿蒙开发了,本篇讲解状态管理的@State装饰器(组件内状态)
一、@State 是什么?
@State装饰的变量,与声明式范式中的其他被装饰变量一样,是私有的,只能从组件内部访问,在声明时必须指定其类型和本地初始化。初始化也可选择使用命名参数机制从父组件完成初始化。
@State装饰的变量拥有以下特点:
@State装饰的变量与子组件中的@Prop装饰变量之间建立单向数据同步,与@Link、@ObjectLink装饰变 量之间建立双向数据同步。
@State装饰的变量生命周期与其所属自定义组件的生命周期相同。
二、使用场景
装饰简单类型的变量
@Entry
@Component
struct MyComponent {
@State count: number = 0;
build() {
Button(`click times: ${this.count}`)
.onClick(() => {
this.count += 1;
})
}
}
装饰class对象类型的变量
class Model{
public value:String
constructor(value:String) {
this.value = value
}
}
@Entry
@Component
struct States {
build(){
Column(){
MyComponent({count:1,increaseBy:2}).width(300)
MyComponent({title:new Model(`Hello World 2`),count:7})
}
}
}
@Component
struct MyComponent {
@State title:Model = new Model(`Hello World`)
@State count:number = 0;
private increaseBy:number = 1;
build(){
Column(){
Text(`${this.title.value}`).margin(10)
Button(`Click to change title`).onClick(()=>{
this.title.value = this.title.value === `Hello ArkUI` ? `Hello World`:`Hello ArkUI`;
})
.width(300)
.margin(10)
Button(`Click to increase count = ${this.count}`)
.onClick(()=>{
this.count += this.increaseBy
})
.width(300)
.margin(10)
}
}
}
从该示例中,我们可以了解到@State变量首次渲染的初始化流程:
- 使用默认的本地初始化:
@State title: Model = new Model('Hello World');
@State count: number = 0;
- 对于@State来说,命名参数机制传递的值并不是必选的,如果没有命名参数传值,则使用本地初始化的默认值:
MyComponent({ count: 1, increaseBy: 2 })