react-chartjs-2折线图使用{x:time,y:data}格式数据无法生效求助
问题原因&修复方案
你代码的核心问题是使用了过时的Chart.js v2配置写法,且配置结构层级错误:
scales是options下的一级配置项,你错误放到了plugins嵌套内- Chart.js v3及以上版本已经废弃了
xAxes数组写法,改为直接用x字段定义x轴配置 - 使用时间轴必须额外安装对应的日期适配器,否则Chart.js无法解析时间格式数据
操作步骤
首先安装必要依赖:
npm install chart.js react-chartjs-2 @canvas-js/chartjs-adapter-date-fns date-fns
修正后完整代码
import React, { Component } from 'react'; import { Line } from 'react-chartjs-2'; // 导入Chart.js核心模块和时间轴、适配器 import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, TimeScale, } from 'chart.js'; import 'chartjs-adapter-date-fns'; // 注册必要组件 ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, TimeScale ); class Grafer extends Component { constructor(props) { super(props); this.state = {}; } data = { datasets: [ { label: 'time-data', data: [ { x: '2021-08-21 18:37:39', y: 2 }, { x: '2021-08-22 18:39:39', y: 3 }, { x: '2021-09-25 18:44:39', y: 1 }, ], borderColor: 'rgba(255,99,132,0.8)', tension: 0.3, }, ], }; options = { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: 'Chart.js Line Chart', }, }, scales: { x: { type: 'time', distribution: 'linear', time: { tooltipFormat: 'yyyy-MM-dd HH:mm:ss' } }, y: { title: { display: false, }, } }, }; render() { return ( <div> <Line data={this.data} options={this.options} /> </div> ); } } export default Grafer;
内容的提问来源于stack exchange,提问作者Christian Lind
相关产品推荐
相关产品推荐

