HarmonyOS7 禁用单选项:用 enabled 做好不可选项

📅 2026/7/21 8:24:40 ✍️ 编辑团队 👁️ 阅读次数
HarmonyOS7 禁用单选项:用 enabled 做好不可选项
文章目录前言交互链路先理清数据和 UI 的对应关系关键实现细节完整代码可以继续扩展的方向前言这组案例开始进入选择类和调节类组件写业务页面时会经常遇到。这个案例围绕Radio 禁用状态展开重点不是把属性背下来而是弄清楚状态、组件和用户操作之间怎么连起来。这篇我会把重点放在状态边界上尽量说清楚它在真实页面里有什么用。交互链路先理清如果把它放到真实项目里常见位置可能是设置页、筛选页、编辑页或者某个需要快速操作的工具面板。用户点一下、选一下、拖一下页面就应该给出明确反馈。维度内容案例主题Radio 禁用状态核心 APIenabled使用场景不可选项文章侧重点状态边界数据和 UI 的对应关系代码结构可以按三层读外层负责页面背景和留白中间卡片承载主要内容内部组件处理具体交互。这样的层级不花哨但维护起来比较舒服。我比较推荐先把状态字段命名清楚。选中项、开关状态、滑块数值最好都能从名字看出用途比随手写flag、value后面省心很多。关键实现细节先看一段连续代码基本能判断这个案例的运行方式。它包含入口组件、状态字段以及一部分核心 UI。EntryComponentstruct DisabledRadioOptions{StateisShow:booleantrueStateselected:stringnormal1build(){Column(){if(this.isShow){Column(){Text(Radio 禁用状态).fontSize(16).fontWeight(FontWeight.Bold).margin({bottom:12})Text(可用选项).fontSize(13).fontColor(THEME_COLOR).margin({bottom:8})Column(){Row(){Radio({value:normal1,group:enabledGroup}).checked(this.selectednormal1).onChange((c:boolean){if(c)this.selectednormal1})这段代码可以拆成几块看State保存当前页面状态用户操作之后会触发 UI 更新。enabled是案例的关键入口真正的行为通常由它和事件回调一起完成。布局属性服务于业务表达选中、禁用、拖动这些状态最好都能在视觉上看出来。完整代码下面是整理后的完整代码。组件名已经改成DisabledRadioOptions共享颜色也内置到当前文件里单独复制出来读会更方便。constCOLOR_OPTIONS:Array{name:string;value:string}[{name:蓝色,value:#4D96FF},{name:绿色,value:#6BCB77},{name:黄色,value:#FFD93D},{name:红色,value:#FF6B6B},{name:紫色,value:#9B59B6},{name:橙色,value:#FFA500},{name:青色,value:#00BCD4},{name:粉色,value:#FF69B4},{name:灰蓝,value:#607D8B},{name:深色,value:#333333}]constPAGE_BG_COLOR:string#F5F6FAconstCARD_BG_COLOR:string#FFFFFFconstTHEME_COLOR:string#4D96FFconstSUBTEXT_COLOR:string#8A8A8AEntryComponentstruct DisabledRadioOptions{StateisShow:booleantrueStateselected:stringnormal1build(){Column(){if(this.isShow){Column(){Text(Radio 禁用状态).fontSize(16).fontWeight(FontWeight.Bold).margin({bottom:12})Text(可用选项).fontSize(13).fontColor(THEME_COLOR).margin({bottom:8})Column(){Row(){Radio({value:normal1,group:enabledGroup}).checked(this.selectednormal1).onChange((c:boolean){if(c)this.selectednormal1})Text(普通选项 A).fontSize(14).margin({left:8})}.margin({bottom:10})Row(){Radio({value:normal2,group:enabledGroup}).checked(this.selectednormal2).onChange((c:boolean){if(c)this.selectednormal2})Text(普通选项 B).fontSize(14).margin({left:8})}}Divider().margin({top:12,bottom:12})Text(禁用选项).fontSize(13).fontColor(COLOR_OPTIONS[8].value).margin({bottom:8})Row(){Radio({value:disabled1,group:enabledGroup}).enabled(false).checked(false)Text(已禁用的选项).fontSize(14).margin({left:8}).fontColor(SUBTEXT_COLOR)}.margin({bottom:10})Row(){Radio({value:disabled2,group:enabledGroup}).enabled(false).checked(true)Text(禁用但已选中).fontSize(14).margin({left:8}).fontColor(SUBTEXT_COLOR)}}.width(100%).padding(16).backgroundColor(CARD_BG_COLOR).borderRadius(12)}Text(禁用单选项Radio 禁用 - 单个选项和整体禁用).fontSize(12).fontColor(SUBTEXT_COLOR).margin({top:12})}.width(100%).height(100%).backgroundColor(PAGE_BG_COLOR).padding(16)}}可以继续扩展的方向继续扩展的话我会把静态选项抽成接口返回的数据再补上空状态和异常状态。示例页面先把核心交互跑通就够了到了业务页面状态边界才是真正容易出问题的地方。