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