HarmonyOS

鸿蒙系统开发初学记录


9.状态管理

<p><img src="https://www.showdoc.com.cn/server/api/attachment/visitFile?sign=ec8d1864216ef4c93e4e6a1fa3911e00&amp;amp;file=file.png" alt="" /></p> <h4>@State 单向 @Prop</h4> <pre><code>//这里编译后会成为全局的一个TitleBar组件,所有不能有重名组件 @Compontent struct TitleBar { //@Prop修饰后不能赋值,这里修改content不会影响外部的值,但修改外部的值会影响这里的值 @Prop content: string build(){ Text(this.content) } } @Entry @Compontent struct MainActivity { //@State修饰后必须赋值 @State title: string = '' build(){ TitleBar({content: this.title}) } }</code></pre> <h4>@State 双向 @Link</h4> <pre><code>//这里编译后会成为全局的一个TitleBar组件,所有不能有重名组件 @Compontent struct TitleBar { //@Link修饰后不能赋值,这里修改content会影响外部的值,修改外部的值也会影响这里的值 @Link content: string build(){ Text(this.content) } } @Entry @Compontent struct MainActivity { //@State修饰后必须赋值 @State title: string = '' build(){ //link参数传递时,使用$变量名进行传递 TitleBar({content: $title}) } }</code></pre> <h4>@Provide 子孙 @Consume</h4> <pre><code>//这里编译后会成为全局的一个TitleBar组件,所有不能有重名组件 @Compontent struct RightMenu { //@Consume修饰后不能赋值,这里修改rightMenu会影响外部的值,修改外部的值也会影响这里的值,括号中是别名,不写变量名就为别名 @Consume('rightMenu') menu: string build(){ Text(this.menu) } } @Compontent struct TitleBar { //@Link修饰后不能赋值,这里修改content会影响外部的值,修改外部的值也会影响这里的值 @Link content: string build(){ Text(this.content) RightMenu() } } @Entry @Compontent struct MainActivity { //@State修饰后必须赋值 @State title: string = '' //@Provide修饰后必须赋值,一般用于传递给后代组件 @Provide('rightMenu') rightMenu: string = '更多' build(){ //link参数传递时,使用$变量名进行传递 TitleBar({content: $title, rightMenu: this.rightMenu}) } }</code></pre>

页面列表

ITEM_HTML