react甘特图实现
使用 react-gantt 库实现
安装 react-gantt 库:
npm install react-gantt
引入库并创建基本甘特图:
import { Gantt } from 'react-gantt';
import 'react-gantt/dist/index.css';
const tasks = [
{
id: '1',
name: '任务1',
start: new Date(2023, 0, 1),
end: new Date(2023, 0, 5)
},
{
id: '2',
name: '任务2',
start: new Date(2023, 0, 3),
end: new Date(2023, 0, 8)
}
];
function App() {
return <Gantt tasks={tasks} />;
}
使用 react-gantt-timeline 实现
安装依赖:
npm install react-gantt-timeline
基本实现代码:
import { GanttRow, Gantt } from 'react-gantt-timeline';
const data = [
{
id: 1,
title: '任务A',
start: new Date(2023, 0, 1),
end: new Date(2023, 0, 5)
}
];
function App() {
return (
<Gantt>
{data.map(item => (
<GanttRow
key={item.id}
title={item.title}
start={item.start}
end={item.end}
/>
))}
</Gantt>
);
}
使用 dhtmlx-gantt 实现
安装 dhtmlx-gantt:
npm install dhtmlx-gantt
基本配置:
import { useEffect } from 'react';
import { gantt } from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css';
function GanttChart() {
useEffect(() => {
gantt.init('gantt_container');
gantt.parse({
data: [
{ id: 1, text: '任务1', start_date: '2023-01-01', duration: 5 }
]
});
}, []);
return <div id="gantt_container" style={{width: '100%', height: '500px'}}></div>;
}
自定义实现方案
使用 SVG 和 React 状态管理创建基础甘特图:
import { useState } from 'react';
const GanttChart = () => {
const [tasks] = useState([
{ id: 1, name: '开发', start: 0, end: 5 },
{ id: 2, name: '测试', start: 3, end: 8 }
]);
return (
<div style={{ width: '100%', overflowX: 'auto' }}>
<svg width="800" height="200">
{tasks.map(task => (
<g key={task.id}>
<rect
x={task.start * 30}
y={task.id * 40}
width={(task.end - task.start) * 30}
height="30"
fill="#4CAF50"
/>
<text x={task.start * 30 + 5} y={task.id * 40 + 20} fill="white">
{task.name}
</text>
</g>
))}
</svg>
</div>
);
};
甘特图功能扩展
添加依赖关系连线(使用 react-gantt-timeline):
<Gantt>
<GanttRow
id="1"
title="任务1"
start={new Date(2023, 0, 1)}
end={new Date(2023, 0, 5)}
/>
<GanttRow
id="2"
title="任务2"
start={new Date(2023, 0, 6)}
end={new Date(2023, 0, 10)}
dependencies={['1']}
/>
</Gantt>
添加进度条显示(dhtmlx-gantt):
gantt.parse({
data: [
{
id: 1,
text: '任务',
start_date: '2023-01-01',
duration: 10,
progress: 0.5
}
]
});






