react实现echarts甘特图
实现步骤
安装必要的依赖包,确保项目中有 echarts 和 react 的基础环境。
npm install echarts echarts-for-react
引入模块
在 React 组件中引入 ReactECharts 和 echarts 核心模块。
import React from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
配置甘特图数据
甘特图的核心是数据格式,通常需要包含任务名称、开始时间、结束时间等信息。以下是一个示例数据格式:
const ganttData = [
{
name: '任务A',
start: '2023-01-01',
end: '2023-01-05'
},
{
name: '任务B',
start: '2023-01-03',
end: '2023-01-08'
},
{
name: '任务C',
start: '2023-01-06',
end: '2023-01-10'
}
];
转换日期为时间戳
ECharts 的甘特图通常需要将日期转换为时间戳以便正确渲染。
const processData = (data) => {
return data.map(item => ({
...item,
startValue: new Date(item.start).getTime(),
endValue: new Date(item.end).getTime()
}));
};
配置 ECharts 选项
定义 ECharts 的配置项,设置坐标轴、系列类型及数据绑定。
const getOption = () => {
const processedData = processData(ganttData);
return {
tooltip: {
trigger: 'axis',
formatter: params => {
const data = params[0].data;
return `${data.name}<br/>开始: ${data.start}<br/>结束: ${data.end}`;
}
},
xAxis: {
type: 'time'
},
yAxis: {
type: 'category',
data: processedData.map(item => item.name)
},
series: [
{
type: 'bar',
data: processedData.map(item => [
item.startValue,
item.endValue,
item.name
]),
encode: {
x: [0, 1],
y: 2
}
}
]
};
};
渲染组件
在 React 组件中使用 ReactECharts 渲染配置好的甘特图。
const GanttChart = () => {
return (
<ReactECharts
option={getOption()}
style={{ height: '400px', width: '100%' }}
/>
);
};
export default GanttChart;
自定义样式调整
如果需要调整甘特图的颜色、间距或其他样式,可以通过修改 series 配置实现。
series: [
{
type: 'bar',
itemStyle: {
color: '#3398DB'
},
barGap: '10%',
barCategoryGap: '20%',
data: processedData.map(item => [
item.startValue,
item.endValue,
item.name
]),
encode: {
x: [0, 1],
y: 2
}
}
]
动态数据更新
如果数据需要动态更新,可以通过 React 的状态管理实现。
const [data, setData] = React.useState(ganttData);
const updateData = (newData) => {
setData(newData);
};
return (
<ReactECharts
option={getOption(data)}
style={{ height: '400px', width: '100%' }}
/>
);
注意事项
- 确保日期格式正确,避免因格式问题导致渲染异常。
- 调整
yAxis的inverse属性可以控制任务列表的排序方向。 - 复杂场景下可能需要结合
dataset和多个series实现更丰富的交互效果。







