鸿蒙 ArkUI @State 响应式数据双向绑定实训博客 一、实训介绍本次实训围绕State状态变量完成三组交互案例分别实现输入框实时回显、独立夜览切换页面、多状态综合联动页面掌握文本数据、布尔开关、页面样式联动刷新的基础交互逻辑。二、案例 1输入框实时回显 Examp1代码etsEntry Component struct Examp1{ State msg:string build() { Column({space:25}){ Text(请输入信息) .fontSize(26) .width(100%) .textAlign(TextAlign.Start) TextInput({text:this.msg,placeholder:}) .width(100%) .height(50) .backgroundColor(#F5F5F5) .fontSize(24) .onChange((value:string){ this.msg value }) Column({space:15}){ Text(你输入的内容是) .fontSize(26) .textAlign(TextAlign.Start) .width(100%) .padding({top:15}) Text(this.msg) .width(100%) .fontSize(24) .fontColor(Color.Black) } .backgroundColor(#F5F5F5) .width(100%) .height(55%) .borderRadius(12) .padding(15) } .width(100%) .height(100%) .padding(20) } }功能说明使用字符串类型State变量绑定输入框输入内容通过onChange实时赋值下方文本框同步展示输入内容实现文本双向联动效果。三、案例 2独立夜览模式切换 Examp2简易版代码etsEntry Component struct Examp2{ State isOpen:boolean false build() { Column(){ Row(){ Text(夜览模式) .fontSize(30) Toggle({type:ToggleType.Switch}) .width(35%) .height(50) .onChange((){ this.isOpen !this.isOpen }) } Text(this.isOpen?夜览模式已开启:夜览模式已关闭) } .width(100%) .height(100%) .backgroundColor(this.isOpen?0xd3d3d3:Color.White) } }功能说明布尔状态绑定滑动开关切换开关时同步修改提示文字与页面整体背景色模拟深色 / 浅色主题切换功能。四、案例 3多状态综合联动页面 Examp2完整版代码etsEntry Component struct Examp2{ State msg:string State isOpen:boolean false State isNight:boolean false build() { Column({space:30}){ Text(请输入信息) .fontSize(32) .width(100%) .textAlign(TextAlign.Start) TextInput({ text: this.msg, placeholder: 请输入内容 }) .width(100%) .height(50) .backgroundColor(#F5F5F5) .fontSize(22) .onChange((value:string){ this.msg value }) Button(this.isOpen ? 开关已打开 : 开关已关闭) .width(100%) .height(55) .fontSize(20) .fontColor(Color.White) .backgroundColor(#007DFF) .borderRadius(30) .onClick((){ this.isOpen !this.isOpen }) Row(){ Text(夜览模式) .fontSize(32) Toggle({type:ToggleType.Switch}) .width(38%) .height(50) .onChange((){ this.isNight !this.isNight }) } .width(100%) Column({space:20}){ Text(你输入的内容是) .fontSize(30) .width(100%) .textAlign(TextAlign.Start) Text(this.msg) .width(100%) .fontSize(26) Row(){ Text(开关的状态) .fontSize(30) Text(this.isOpen ? 开启 : 关闭) .fontSize(30) .fontColor(Color.Red) } .width(100%) Row(){ Text(夜览模式) .fontSize(30) Text(this.isNight ? 已开启 : 已关闭) .fontSize(30) .fontColor(Color.Red) } .width(100%) } .width(100%) .height(52%) .backgroundColor(#F5F5F5) .borderRadius(14) .padding(25) } .width(100%) .height(100%) .padding(30) .backgroundColor(this.isNight ? 0xd3d3d3 : Color.White) } }功能说明页面同时维护三组独立状态文本输入状态、按钮开关状态、夜览模式状态。输入框输入实时展示点击按钮切换自身文字并同步状态提示滑动开关控制页面背景色底部实时展示全部状态信息实现多数据同时联动刷新。五、实训总结State是 ArkUI 实现动态交互核心被修饰变量修改后页面自动刷新字符串类型状态可绑定 TextInput完成输入内容实时回显布尔类型状态搭配 Button、Toggle 控件可控制文字、页面背景等样式动态切换单页面可同时定义多个State变量互不干扰实现多组交互逻辑共存。