先放一个效果:
组件代码:
import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
const LineChart = ({powerData}) => {
const chartRef = useRef(null);
const [drawing, setDrawing] = useState(false);
useEffect(() => {
const myChart = echarts.init(chartRef.current);
const updateChart = () => {
const option = {
title: {
text: '折线图',
},
xAxis: {
type: 'category',
data: powerData.map(entry => entry.time),
},
yAxis: {
type: 'value',
name: '电量',
},
series: [
{
name: '电量',
type: 'line',
smooth: true,
showSymbol: false,
data: powerData.map(entry => entry.power),
animation: false,
},
],
};
myChart.setOption(option);
};
updateChart();
const handleChartClick = () => {
setDrawing(true);
};
const handleChartMouseMove = e => {
if (drawing) {
const [xAxisValue, yAxisValue] = myChart.convertFromPixel('grid', [e.offsetX, e.offsetY]);
powerData[xAxisValue].power = yAxisValue;
updateChart();
}
};
const handleChartMouseUp = () => {
if (drawing) {
setDrawing(false);
}
};
myChart.getZr().on('mousedown', handleChartClick);
myChart.getZr().on('mousemove', handleChartMouseMove);
myChart.getZr().on('mouseup', handleChartMouseUp);
return () => {
myChart.dispose();
};
}, [powerData, drawing]);
return <div ref={chartRef} style={{ width: '100%', height: '400px' }} />;
};
export default LineChart;
父组件:
import React from 'react';
import LineChart from './LineChart';
const App = () => {
// 假设这是您的电量数据
const powerData = [
{ time: '2023-01-01 00:00', power: 10 },
{ time: '2023-01-01 01:00', power: 15 },
// 其他数据点
];
return (
<div className="App">
<LineChart powerData={powerData} />
</div>
);
};
export default App;
做之前查到的都是拖拽折线,有需要的话echarts官网有: