在 OpenHarmony(ArkUI,eTS/ArkTS) 中,图表的“动态更新”本质上是 数据状态变化 → UI 自动刷新。常见做法有以下几种,按使用场景由简到复杂说明。
@ohos/mpchart(常用三方图表库)@State 管理数据import { LineChart, LineData, LineDataSet } from '@ohos/mpchart'
@Entry
@Component
struct ChartPage {
@State dataPoints: number[] = [1, 3, 2, 5, 4]
build() {
Column() {
LineChart({ data: this.getLineData() })
Button('更新数据')
.onClick(() => {
// 动态修改数据
this.dataPoints = this.dataPoints.map(v => v + Math.random() * 2)
})
}
}
getLineData(): LineData {
const dataSet = new LineDataSet(this.dataPoints, '示例')
return new LineData([dataSet])
}
}
✅ 特点
如果你用的是 Canvas 自己画图表:
@State 数据变化Canvas 在 onDraw 中重绘@Entry
@Component
struct CanvasChart {
@State values: number[] = [10, 20, 30]
build() {
Column() {
Canvas(this.context)
.width('100%')
.height(200)
.onReady(() => this.draw())
Button('刷新')
.onClick(() => {
this.values = this.values.map(v => v + 5)
})
}
}
@State context: CanvasRenderingContext2D = new CanvasRenderingContext2D()
draw() {
this.context.clearRect(0, 0, 400, 200)
this.values.forEach((v, i) => {
this.context.fillRect(i * 50, 200 - v, 30, v)
})
}
// 数据变化后重绘
aboutToUpdate() {
this.draw()
}
}
setIntervalaboutToAppear() {
setInterval(() => {
this.dataPoints = [...this.dataPoints.slice(1), Math.random() * 10]
}, 1000)
}
⚠️ 注意:
clearIntervalthis.dataPoints[0] = 10 // ❌ 不会触发刷新
✅ 正确方式
this.dataPoints = [...this.dataPoints]
| 场景 | 推荐方案 |
|---|---|
| 普通业务图表 | mpchart / 官方图表 |
| 高度自定义 | Canvas |
| 实时数据 | 定时器 + State |
| 大数据 | 分页 / 采样 |
如果你能说明:
我可以直接给你 可运行的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。