
文章目录前言适合放在哪些页面里页面结构拆一下核心逻辑说明完整代码最后提醒一句前言这组案例开始进入选择类和调节类组件写业务页面时会经常遇到。这个案例围绕RadioGroup 状态控制展开重点不是把属性背下来而是弄清楚状态、组件和用户操作之间怎么连起来。这篇我会把重点放在互斥逻辑上尽量说清楚它在真实页面里有什么用。适合放在哪些页面里如果把它放到真实项目里常见位置可能是设置页、筛选页、编辑页或者某个需要快速操作的工具面板。用户点一下、选一下、拖一下页面就应该给出明确反馈。维度内容案例主题RadioGroup 状态控制核心 APIchecked使用场景状态控制文章侧重点互斥逻辑页面结构拆一下代码结构可以按三层读外层负责页面背景和留白中间卡片承载主要内容内部组件处理具体交互。这样的层级不花哨但维护起来比较舒服。我比较推荐先把状态字段命名清楚。选中项、开关状态、滑块数值最好都能从名字看出用途比随手写flag、value后面省心很多。核心逻辑说明先看一段连续代码基本能判断这个案例的运行方式。它包含入口组件、状态字段以及一部分核心 UI。EntryComponentstruct RadioStateController{StateisShow:booleantrueStateselectedPlatform:stringandroidbuild(){Column(){if(this.isShow){Column(){Text(RadioGroup 单选组).fontSize(16).fontWeight(FontWeight.Bold).margin({bottom:12})Column(){Row(){Radio({value:harmonyos,group:platformGroup}).checked(this.selectedPlatformharmonyos).onChange((checked:boolean){if(checked)this.selectedPlatformharmonyos})Text(HarmonyOS).fontSize(15).margin({left:8})}.margin({bottom:10})这段代码可以拆成几块看State保存当前页面状态用户操作之后会触发 UI 更新。checked是案例的关键入口真正的行为通常由它和事件回调一起完成。布局属性服务于业务表达选中、禁用、拖动这些状态最好都能在视觉上看出来。完整代码下面是整理后的完整代码。组件名已经改成RadioStateController共享颜色也内置到当前文件里单独复制出来读会更方便。constPAGE_BG_COLOR:string#F5F6FAconstCARD_BG_COLOR:string#FFFFFFconstTHEME_COLOR:string#4D96FFconstSUBTEXT_COLOR:string#8A8A8AEntryComponentstruct RadioStateController{StateisShow:booleantrueStateselectedPlatform:stringandroidbuild(){Column(){if(this.isShow){Column(){Text(RadioGroup 单选组).fontSize(16).fontWeight(FontWeight.Bold).margin({bottom:12})Column(){Row(){Radio({value:harmonyos,group:platformGroup}).checked(this.selectedPlatformharmonyos).onChange((checked:boolean){if(checked)this.selectedPlatformharmonyos})Text(HarmonyOS).fontSize(15).margin({left:8})}.margin({bottom:10})Row(){Radio({value:android,group:platformGroup}).checked(this.selectedPlatformandroid).onChange((checked:boolean){if(checked)this.selectedPlatformandroid})Text(Android).fontSize(15).margin({left:8})}.margin({bottom:10})Row(){Radio({value:ios,group:platformGroup}).checked(this.selectedPlatformios).onChange((checked:boolean){if(checked)this.selectedPlatformios})Text(iOS).fontSize(15).margin({left:8})}}Text(当前选择:${this.selectedPlatform}).fontSize(13).fontColor(THEME_COLOR).margin({top:12}).padding(10).backgroundColor(THEME_COLOR10).borderRadius(8).width(100%).textAlign(TextAlign.Center)}.width(100%).padding(16).backgroundColor(CARD_BG_COLOR).borderRadius(12)}Text(单选状态控制器RadioGroup 单选组 - State 控制选中项).fontSize(12).fontColor(SUBTEXT_COLOR).margin({top:12})}.width(100%).height(100%).backgroundColor(PAGE_BG_COLOR).padding(16)}}最后提醒一句继续扩展的话我会把静态选项抽成接口返回的数据再补上空状态和异常状态。示例页面先把核心交互跑通就够了到了业务页面状态边界才是真正容易出问题的地方。