鸿蒙 评分组件Rating

本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

Rating组件是鸿蒙(HarmonyOS)中用于展示和收集评分的UI组件,支持星级评分、自定义图标、半星评分等功能。

一、基础用法

1. 基本评分展示

// 基础评分组件
@Entry
@Component
struct RatingExample {
  @State rating: number = 3.5 // 默认3.5星

  build() {
    Column() {
      // 基本使用
      Rating({
        rating: this.rating,
        indicator: false // 非指示器模式(可交互)
      })
      .stars(5) // 总星数
      .stepSize(0.5) // 步长0.5(支持半星)
      .onChange((value: number) => {
        this.rating = value // 评分变化时更新
        console.log('当前评分:', value)
      })
      
      Text(`当前评分: ${this.rating}`).margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

二、核心API

1. 评分控制属性

API类型默认值描述示例
ratingnumber0当前评分值.rating(3.5)
starsnumber5总星数.stars(10)
stepSizenumber0.5评分变化步长.stepSize(1)
indicatorbooleanfalse是否为指示器模式(不可交互).indicator(true)

2. 样式定制API

API类型默认值描述示例
starStyle{ background: string, foreground: string, secondary?: string }-星形样式.starStyle({ background: '#CCCCCC', foreground: '#FFD700' })
widthLength父容器宽度组件宽度.width(200)
heightLength父容器高度组件高度.height(40)

3. 交互事件API

API参数描述示例
onChange(value: number) => void评分变化回调.onChange((value) => {})
onAppear() => void组件出现回调.onAppear(() => {})
onDisAppear() => void组件消失回调.onDisAppear(() => {})

三、功能示例

1. 自定义星形样式

@Entry
@Component
struct CustomRatingExample {
  @State rating: number = 2.5

  build() {
    Column() {
      Rating()
        .rating(this.rating)
        .stars(5)
        .stepSize(0.5)
        .starStyle({
          background: '#DDDDDD', // 未选中的星颜色
          foreground: '#FF6347', // 选中的星颜色
          secondary: '#FFA07A' // 部分选中的星颜色(半星)
        })
        .width(300)
        .height(50)
        .onChange((value: number) => {
          this.rating = value
        })
      
      Text(`自定义样式评分: ${this.rating}`).margin(10)
    }
    .padding(20)
  }
}

2. 不同尺寸的Rating

@Entry
@Component
struct SizeRatingExample {
  @State smallRating: number = 3
  @State mediumRating: number = 4
  @State largeRating: number = 2.5

  build() {
    Column() {
      // 小尺寸
      Rating({ rating: this.smallRating })
        .width(150)
        .height(20)
        .onChange((value) => { this.smallRating = value })
      
      Text(`小尺寸: ${this.smallRating}`).margin(10)

      // 中尺寸
      Rating({ rating: this.mediumRating })
        .width(200)
        .height(30)
        .onChange((value) => { this.mediumRating = value })
      
      Text(`中尺寸: ${this.mediumRating}`).margin(10)

      // 大尺寸
      Rating({ rating: this.largeRating })
        .width(250)
        .height(40)
        .onChange((value) => { this.largeRating = value })
      
      Text(`大尺寸: ${this.largeRating}`).margin(10)
    }
  }
}

3. 只读评分指示器

@Entry
@Component
struct IndicatorRatingExample {
  @State currentScore: number = 4.2

  build() {
    Column() {
      // 只读评分展示
      Rating({ 
        rating: this.currentScore,
        indicator: true // 设置为指示器模式
      })
      .starStyle({
        background: '#EEEEEE',
        foreground: '#FFA500'
      })
      
      Slider({
        value: this.currentScore,
        min: 0,
        max: 5,
        step: 0.1
      })
      .onChange((value) => {
        this.currentScore = value
      })
      .width('80%')
      
      Text(`动态评分值: ${this.currentScore.toFixed(1)}`)
        .fontSize(16)
        .margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

四、高级功能实现

1. 自定义图标Rating

@Entry
@Component
struct CustomIconRating {
  @State rating: number = 3.5

  build() {
    Column() {
      // 使用自定义图标
      Rating({ rating: this.rating })
        .stars(5)
        .stepSize(0.5)
        .starStyle({
          background: $r('app.media.ic_star_outline'), // 未选中图标
          foreground: $r('app.media.ic_star_filled'), // 选中图标
          secondary: $r('app.media.ic_star_half') // 半星图标
        })
        .width(250)
        .height(40)
        .onChange((value) => {
          this.rating = value
        })
      
      Text(`自定义图标评分: ${this.rating}`)
        .fontSize(16)
        .margin(10)
    }
  }
}

2. 动态星星数量

@Entry
@Component
struct DynamicStarRating {
  @State starCount: number = 5
  @State currentRating: number = 0

  build() {
    Column() {
      // 动态星星数量
      Rating({ rating: this.currentRating })
        .stars(this.starCount)
        .width(200)
        .height(30)
        .onChange((value) => {
          this.currentRating = value
        })
      
      Row() {
        Button('3星')
          .onClick(() => { this.starCount = 3 })
        
        Button('5星')
          .onClick(() => { this.starCount = 5 })
          .margin(10)
        
        Button('10星')
          .onClick(() => { this.starCount = 10 })
      }
      .margin(20)
      
      Text(`当前: ${this.starCount}星制, 评分: ${this.currentRating}`)
        .fontSize(16)
    }
  }
}

3. 评分与动画结合

@Entry
@Component
struct AnimatedRating {
  @State rating: number = 0
  @State scale: number = 1

  build() {
    Column() {
      // 带动画效果的Rating
      Rating({ rating: this.rating })
        .stars(5)
        .width(200)
        .height(40)
        .scale({ x: this.scale, y: this.scale })
        .onChange((value) => {
          // 评分变化时触发动画
          this.rating = value
          this.scale = 1.2
          setTimeout(() => {
            this.scale = 1
          }, 300)
        })
      
      Text(`当前评分: ${this.rating}`)
        .fontSize(16)
        .margin(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

五、注意事项

  1. 性能考虑

    • 避免在频繁变化的组件中使用复杂的Rating样式
    • 大量Rating组件时考虑使用轻量级实现
  2. 用户体验

    • 常用star数量为5或10
    • 步长0.5(半星)或1(整星)最符合用户习惯
    • 提供明确的评分指引文字
  3. 样式适配

    • 在不同设备上测试Rating的显示效果
    • 考虑深色/浅色模式下的颜色适配
  4. 交互反馈

    • 评分变化时提供视觉或触觉反馈
    • 重要评分操作可增加确认步骤

Rating组件是鸿蒙系统中非常实用的评分输入控件,通过灵活使用各种API可以实现多样化的评分需求。根据具体场景选择合适的配置方式。

<think>好的,我现在需要帮助用户了解鸿蒙系统中的Rating组件的使用方法。首先,我需要回顾一下用户提供的引用内容,看看有哪些相关信息可以利用。 根据引用[1],鸿蒙系统提供了多种UI组件,包括基础组件,而Rating组件应该属于基础组件之一。引用[2]和[3]提到在JS中使用Rating组件,而引用[4]则给出了具体的HML和CSS代码示例。这说明Rating组件可以通过声明式UI在HML文件中使用,并且可以通过CSS进行样式调整。 接下来,我需要整理Rating组件的核心属性和事件。引用[4]中提到了numstars和rating属性,分别设置总星数和当前评分。同时,引用[3]提到使用onchange事件来处理评分变化,并使用$idx获取索引值。这些是基本的使用方法。 然后,我需要考虑如何结构化回答。应该包括基本用法、样式自定义、事件处理以及可能的高级用法,比如动态绑定数据或结合列表渲染。同时,要确保代码示例符合用户提到的JS语法,并展示HML、CSS和JS的配合。 另外,需要注意用户可能的问题,比如如何调整图标大小或颜色,如何处理用户交互后的逻辑,这些都需要在回答中涵盖。同时,要引用正确的来源,例如引用[3]和[4]中的代码示例,确保信息准确。 最后,要生成相关问题,帮助用户进一步学习,比如性能优化、自定义样式或与其他组件的结合使用。这些需要基于已有的引用内容,确保问题相关且有依据。</think>### 鸿蒙系统 Rating 组件使用方法 Rating 组件鸿蒙系统(HarmonyOS)中用于实现星级评分的 UI 组件,支持通过简单的属性配置实现交互式评分功能。以下是其核心用法和实现细节: --- #### 一、基本用法 1. **声明组件** 在 `.hml` 文件中使用 `<rating>` 标签声明组件,并通过属性设置默认值: ```html <div class="container"> <rating numstars="5" rating="3" onchange="onRatingChange"></rating> </div> ``` - `numstars`:总星数(默认 5 星) - `rating`:默认选中星数(支持小数,如 `3.5`) - `onchange`:绑定评分变化事件[^3][^4] 2. **样式定义(`.css` 文件)** 调整组件尺寸和布局: ```css .container { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; } rating { width: 80%; height: 150px; star-color: #FFD700; /* 未选中颜色 */ selected-star-color: #FFA500; /* 选中颜色 */ } ``` 支持通过 CSS 自定义星标颜色、大小等样式[^4]。 3. **事件处理(`.js` 文件)** 实现评分变化的逻辑响应: ```javascript export default { onRatingChange(e) { console.log("当前评分:" + e.rating); // 获取用户选择的星数 } } ``` 通过 `e.rating` 获取用户操作后的评分值[^3]。 --- #### 二、高级用法 1. **动态数据绑定** 结合数据模型实现动态更新: ```html <rating numstars="{{totalStars}}" rating="{{currentRating}}" onchange="updateRating"></rating> ``` ```javascript export default { data: { totalStars: 5, currentRating: 2.5 }, updateRating(e) { this.currentRating = e.rating; // 更新数据模型 } } ``` 2. **自定义星标图标** 可通过替换默认图标资源实现个性化样式(需在 `resources` 目录中添加图片文件): ```css rating { star-image: url("/common/star_unselected.png"); selected-star-image: url("/common/star_selected.png"); } ``` 3. **列表渲染结合** 在列表中使用评分组件(如商品评价列表): ```html <list> <list-item for="{{items}}"> <rating numstars="5" rating="{{$item.score}}" onchange="onItemRate($idx)"></rating> </list-item> </list> ``` ```javascript onItemRate(index) { console.log("第" + index + "项的评分已更新"); } ``` 通过 `$idx` 获取列表项索引。 --- #### 三、注意事项 1. **兼容性** Rating 组件鸿蒙 API 版本 ≥ 5,建议使用最新 DevEco Studio 开发工具。 2. **性能优化** 频繁更新评分时,避免直接操作 DOM,优先使用数据绑定[^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值