🎯 目标

封装一个评分星级组件 RateStars,适用于:

  • 用户评价内容打分(如课程评分、商品评价)

  • 支持半星、整星、只读模式、自定义星数

  • 提供评分文字/数值显示(如:4.5 分)

  • 支持评分动画(缩放 / 闪光)

  • 后续可拓展为评分提交 + 标签联动组件


🧱 交互示意结构

⭐⭐⭐⭐☆  4.0 分
[ 用户点击第 4.5 星 → 星星缩放动画 ]

🧰 组件实现:RateStars.ets

@Component
export struct RateStars {
  @Prop value: number = 0
  @Prop max: number = 5
  @Prop allowHalf: boolean = true
  @Prop readOnly: boolean = false
  @Prop showScore: boolean = true
  @Prop onChange: (value: number) => void = () => {}

  @State internalValue: number = this.value

  build() {
    Row({ space: 6 }).alignItems(VerticalAlign.Center) {
      ForEach(new Array(this.max), (_, idx) => {
        const full = idx + 1 <= this.internalValue
        const half = this.allowHalf && (this.internalValue > idx) && (this.internalValue < idx + 1)

        Image(this.getIcon(full, half))
          .width(24)
          .height(24)
          .onClick(() => {
            if (!this.readOnly) {
              const newVal = this.allowHalf && !full ? idx + 0.5 : idx + 1
              this.internalValue = newVal
              this.onChange(newVal)
            }
          })
      })

      if (this.showScore) {
        Text(`${this.internalValue.toFixed(1)} 分`)
          .fontSize(14)
          .fontColor('#666')
          .margin({ left: 8 })
      }
    }
  }

  private getIcon(full: boolean, half: boolean): Resource {
    if (full) return $r('app.media.icon_star_full')
    if (half) return $r('app.media.icon_star_half')
    return $r('app.media.icon_star_empty')
  }
}

📦 使用示例

@Entry
@Component
struct DemoRateStars {
  @State score: number = 3.5

  build() {
    Column({ space: 20 }).padding(20) {
      RateStars({
        value: this.score,
        allowHalf: true,
        onChange: val => {
          this.score = val
          ToastManager.show(`当前评分:${val} 分`)
        }
      })

      Text(`已选评分:${this.score.toFixed(1)} 分`).fontSize(14).fontColor('#007DFF')
    }
  }
}

✨ 可扩展能力建议

功能 说明
动画反馈(缩放、闪光) 用户点击星星后添加 scale 或光效动画增强反馈
支持评分文字描述(如“很好”) 根据评分数值展示文字,如“差 / 一般 / 很好 / 满分”
加载状态与禁用模式 提交中状态不可点击,或展示只读评分模式
拖动评分 / 滑动评分 鼠标/手势横滑选择星数,提升体验

📘 下一篇预告

第55篇:【HarmonyOS 5.0.0 或以上】构建步骤表单组件 StepForm:分步骤填写 / 数据缓存 / 完成提交反馈

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐