ArkTS的变量状态管理
一、@State动态渲染UI页面
语法:
@State 成员变量: type = 值
这个时候,如果在组件中动态修改这个成员变量,UI页面也会同步更改
但是,当存在嵌套的时候,UI渲染只会动态修改第一层的修改,除非整体修改,
示例:
@State cat: Cat = {name: ''color: {value: ''}
}
当你去修改 name,和 color(整体)时,可以做到动态渲染,但是如果你单独去修改 value ,则不会做到动态渲染
二、父子组件间的变量通信
1. 父传子,子传孙
使用@Prop来实现上面这种单项传递
步骤:
I. 在子组件的变量上面添上注解 @Prop 表示这个参数可以接受父组件传过来的值
II.在父组件调用时,对该参数赋值
示例:
子组件:
@Component
export default struct SonCom {@Prop mesForFather: string = '子组件的默认值' // 该参数可以接受父组件的传值build() {Column() {Text(this.mesForFather).fontSize(20).height(50).textAlign(TextAlign.Center)}.width("100%").height(50).borderRadius(20).border({width: 1})}
}
父组件:
import SonCom from '../components/SonCom'@Entry
@Component
struct Index {build() {Column() {Column({ space: 15 }) {SonCom()SonCom({ mesForFather: '这是父组件传的文字' }) // 对 mesForFather 进行传值,注意传值方法}.width('80%').backgroundColor('#D4F6FF').height(500).justifyContent(FlexAlign.Center)}.width("100%")}
}
2. 子传父,父传子
使用@Link实现父组件和子组件的双向同步传递,这就很像vue的数据双向绑定了
使用步骤:
I. 将父组件的状态属性传递给子组件
II.子组件通过@Link修饰即可
示例:
@Entry
@Component
struct Index {@State count: number = 0build() {Column() {Text('父组件').fontSize(30)Text(this.count.toString())Button('修改数据').onClick(() => {this.count++;})SonComponent({ count: this.count })}.width("100%").height('100%')}
}@Component
struct SonComponent {@Link count: numberbuild() {Column() {Text('我是子组件').fontSize(20)Text(this.count.toString())Button('修改数据').onClick(() => {this.count++;})}}
}
三、@Observed,@ObjectLink嵌套对象的动态UI渲染
由于@State只能对于第一次数据得到修改的时候,UI层才会动态渲染,
所以就引申出上面两个装饰器来对嵌套对象和数组进行动态渲染。
注意:
@ObjectLink不能用在@Entry修饰的组件中
使用步骤:
- 定义一个类或者接口,使用@Observed监听它的改变情况
- 在需要调用上面类或者接口的成员变量前加上@ObjectLink, 表示它的改变会引起监听,以便于动态渲染UI界面
示例:
interface IPerson {id: numbername: stringage: number
}// Observed 观察,会监视下面这个类的更改,只要有那内容出现了改变,那就会主动刷新UI界面
@Observed
class Person implements IPerson {id: numbername: stringage: numberconstructor(config: IPerson) {this.id = config.idthis.name = config.namethis.age = config.age}
}@Entry
@Component
struct ObservedAndLink {@State personList: Person[] = [new Person({id: 1,name: '张三',age: 18}),new Person({id: 2,name: '李四',age: 19}),new Person({id: 3,name: '王五',age: 20})]build() {Column() {Text('父组件').fontSize(30)List({ space: 10 }) {ForEach(this.personList, (item: Person, index: number) => {ItemCom({info: item,// addAge: () => {// // item.age++// // this.personList.splice(index, 1, item)// }})})}}}
}@Component
struct ItemCom {
//建立监听依赖,当info里面的值改变时,引起UI界面@ObjectLink info: PersonaddAge = () => {}build() {ListItem() {Row({ space: 10 }) {Text('姓名' + this.info.name)Text('年龄' + this.info.age)Blank()Button('修改数据').onClick(() => {this.info.age++// this.addAge()})}}.backgroundColor(Color.Pink).padding(10).width('100%')}
}