Skip to content

评分条组件

项目开发中可能会有设置评分的需求,比如给用户一个弹窗,让用户给当前 APP 设置评分等场景,ArkUI 开发框架提供了评分条组件 Rating ,本节笔者介绍一下它的简单使用。

Rating 定义介绍

bash

interface RatingInterface {
  (options?: { rating: number; indicator?: boolean }): RatingAttribute;
}

options

Rating 的配置参数

  • rating 表示设置当前评分值,

  • indicator 表示是否可以操作,设置为 true 表示评分条是一个指示条,不可操作,false 表示可以操作的评分条。

简单样式如下:

bash

@Entry @Component struct RatingTest {
  build() {
    Column({ space: 10 }) {
      Rating({ rating: 0, indicator: true })  // 设置不可操作,默认值为0
        .width(220)
        .height(60)

      Rating({ rating: 0, indicator: false }) // 设置可操作,默认值为0
        .width(220)
        .height(60)
    }
    .width('100%')
    .height("100%")
    .padding(10)
  }
}

样例运行效果如下图所示:

图片

由运行效果可知,当设置 indicator 为 true 时, Rating 不可操作。

Rating 属性介绍

bash

declare class RatingAttribute extends CommonMethod<RatingAttribute> {
  stars(value: number): RatingAttribute;
  stepSize(value: number): RatingAttribute;
  starStyle(value: { backgroundUri: string; foregroundUri: string; secondaryUri?: string }): RatingAttribute;
}
  • stars:设置星星的总数,默认值为 5 。

  • stepSize:设置操作评级的步长,默认值为 0.5 。

  • starStyle:设置星星的样式,各参数说明如下:

    1. backgroundUri:设置未选中的星星的图片,仅支持本地图片。
    2. foregroundUri:设置选中的星星的图片,仅支持本地图片。
    3. secondaryUri:部分选中的星级的图片路径,仅支持本地图片。

简单样例如下所示:

bash

@Entry @Component struct RatingTest {

  build() {
    Column({ space: 10 }) {
      Rating({
        rating: 3,       // 设置默认值为3
        indicator: false // 设置可以操作
      })
        .width(220)
        .height(40)
        .stars(8)        // 设置总共有8颗星星
        .stepSize(0.5)   // 设置步长为0.5
    }
    .width('100%')
    .height("100%")
    .padding(10)
  }
}

样例运行效果如下图所示:

图片

Rating 事件介绍

bash

declare class RatingAttribute extends CommonMethod<RatingAttribute> {
  onChange(callback: (value: number) => void): RatingAttribute;
}
  • onChange:评分条评分发生改变时触发该回调。

简单样例如下所示:

bash

@Entry @Component struct RatingTest {

  @State rating: number = 1

  build() {
    Column({ space: 10 }) {
      Rating({
        rating: this.rating,
        indicator: false
      })
        .width(220)
        .height(40)
        .stars(8)
        .stepSize(0.5)
        .onChange((value) => {
          this.rating = value;
        })

      Text(`总分数:${this.rating}`)
        .fontSize(22)
        .width(220)

    }
    .width('100%')
    .height("100%")
    .padding(10)
  }

}

样例运行效果如下图所示:

图片