前言
@State是 ArkTS 本地响应式状态核心装饰器,变量变更后页面自动刷新,是表单、开关交互的基础。本文分 3 个梯度案例,从最简单输入框到多控件联动,循序渐进掌握状态绑定逻辑。
一、基础入门:单输入框实时回显(字符串状态)
仅 1 个字符串状态,实现输入内容实时同步展示,看懂双向绑定底层逻辑。
完整代码
@Entry
@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)
}
}
核心逻辑
效果

二、进阶实战:Toggle 布尔状态切换页面样式
使用布尔类型状态,搭配开关组件实现全局页面样式切换,掌握布尔值状态联动。
完整代码
@Entry
@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)
}
}
核心逻辑


三、综合实战:多状态多控件联动(业务通用模板)
整合字符串、双布尔状态,同时承载输入框、按钮、Toggle 三类交互,还原真实表单开发场景。
完整代码
@Entry
@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)
}
}
状态分工
效果







