#跟着晓明学鸿蒙# HarmonyOS NEXT多维度评分功能实现
在餐厅评分系统中,需要对多个维度进行评分,如口味、服务、环境和性价比等。本篇文章将介绍如何使用Counter组件实现多维度评分功能,并通过组件复用提高代码的可维护性。这篇文章展示了如何实现一个多维度评分功能,主要包括了Counter组件的配置和使用、评分项组件的复用设计以及评分计算和描述的实现。通过组件复用和状态管理,构建了一个既灵活又容易维护的多维度评分系统。
·

目录
- 案例介绍
- 代码实现
- 代码详解
- 评分功能实现
- 评分项组件
- 评分区域实现
- 总结
案例介绍
在餐厅评分系统中,需要对多个维度进行评分,如口味、服务、环境和性价比等。本篇文章将介绍如何使用Counter组件实现多维度评分功能,并通过组件复用提高代码的可维护性。
代码实现
@Entry
@Component
struct RestaurantRatingPage {
// 评分状态变量
@State tasteRating: number = 3
@State serviceRating: number = 3
@State environmentRating: number = 3
@State priceRating: number = 3
// 计算总体评分
private getOverallRating(): number {
return (this.tasteRating + this.serviceRating + this.environmentRating + this.priceRating) / 4
}
// 获取评分描述
private getRatingDescription(rating: number): string {
if (rating < 2) return '差'
if (rating < 3) return '一般'
if (rating < 4) return '良好'
if (rating < 5) return '优秀'
return '极佳'
}
build() {
Column() {
// 评分区域
Column() {
Text('评分详情')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 15 })
// 口味评分
this.RatingItem('口味', '评价菜品的味道和品质', this.tasteRating, (value) => {
this.tasteRating = value
})
// 服务评分
this.RatingItem('服务', '评价服务员的态度和效率', this.serviceRating, (value) => {
this.serviceRating = value
})
// 环境评分
this.RatingItem('环境', '评价餐厅的装修和氛围', this.environmentRating, (value) => {
this.environmentRating = value
})
// 性价比评分
this.RatingItem('性价比', '评价价格与品质的匹配度', this.priceRating, (value) => {
this.priceRating = value
})
}
.width('100%')
.padding(15)
.backgroundColor(Color.White)
.borderRadius(10)
.margin({ bottom: 20 })
}
}
@Builder
RatingItem(title: string, description: string, rating: number, onChange: (value: number) => void) {
Row() {
Column() {
Text(title)
.fontSize(16)
.fontWeight(FontWeight.Medium)
.margin({ bottom: 5 })
Text(description)
.fontSize(14)
.fontColor('#666666')
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
Row() {
Counter() {
value: rating
min: 1
max: 5
step: 1
onChange: onChange
}
Text('分')
.fontSize(14)
.margin({ left: 5 })
}
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.alignItems(VerticalAlign.Center)
.padding({ top: 10, bottom: 10 })
.borderBottom({ width: 1, color: '#EEEEEE' })
}
}
代码详解
评分功能实现
-
状态管理:
- 使用@State装饰器定义四个评分维度的状态变量
- 每个维度默认值设为3分
-
评分计算:
- getOverallRating方法计算四个维度的平均分
- getRatingDescription方法根据分数返回对应的评价描述
评分项组件
-
组件定义:
- 使用@Builder装饰器创建RatingItem复用组件
- 接收标题、描述、当前评分和onChange回调参数
-
布局结构:
- 使用Row实现左右布局
- 左侧Column显示标题和描述
- 右侧放置Counter组件和单位文本
-
Counter组件配置:
- 设置评分范围1-5分
- 步长为1
- 通过onChange回调更新状态
评分区域实现
-
区域布局:
- 使用Column组件包裹所有评分项
- 添加标题和适当的样式
-
评分项复用:
- 为每个维度创建RatingItem实例
- 传入相应的标题、描述和状态变量
- 实现评分更新回调
总结
这篇文章展示了如何实现一个多维度评分功能,主要包括了Counter组件的配置和使用、评分项组件的复用设计以及评分计算和描述的实现。通过组件复用和状态管理,构建了一个既灵活又容易维护的多维度评分系统。
更多推荐


所有评论(0)