在React的Gantt图中添加当前日期红线及设置任务颜色
React Google Gantt图自定义需求解决方案
一、添加当前日期红色竖线
Google Gantt图没有内置的当前日期线配置,需要通过监听图表的ready事件,手动绘制SVG线条实现:
- 监听图表
ready事件,获取图表实例与容器 - 计算当前日期对应的X轴像素位置
- 创建红色竖线元素并添加到图表SVG容器中
代码示例:
import { Chart } from "react-google-charts"; const App = () => { const handleChartReady = (chartWrapper) => { const chart = chartWrapper.getChart(); const container = chart.getContainer(); const currentDate = new Date(); // 获取当前日期对应的X坐标 const xPos = chart.getChartLayoutInterface().getXLocation(currentDate); // 创建红色虚线竖线 const line = document.createElementNS('http://www.w3.org/2000/svg', 'line'); line.setAttribute('x1', xPos.toString()); line.setAttribute('x2', xPos.toString()); line.setAttribute('y1', '0'); line.setAttribute('y2', container.offsetHeight.toString()); line.setAttribute('stroke', '#ff0000'); line.setAttribute('stroke-width', '2'); line.setAttribute('stroke-dasharray', '5,3'); // 可选,设置虚线样式 // 将线条添加到图表的SVG容器中 container.querySelector('svg')?.appendChild(line); }; // 甘特图基础数据与配置 const data = [ ['Task ID', 'Task Name', 'Resource', 'Start Date', 'End Date', 'Duration', 'Percent Complete'], ['task1', '需求分析', '张三', new Date(2024, 4, 1), new Date(2024, 4, 7), null, 100], ['task2', 'UI设计', '李四', new Date(2024, 4, 5), new Date(2024, 4, 15), null, 60], ['task3', '后端开发', '王五', new Date(2024, 4, 12), new Date(2024, 4, 25), null, 30], ]; const options = { height: 400, gantt: { trackHeight: 30, }, }; return ( <Chart chartType="Gantt" data={data} options={options} ready={handleChartReady} width="100%" /> ); }; export default App;
二、设置已完成/部分完成任务为深灰色
官方全局配置taskFillColor无法单独指定任务状态的颜色,需通过数据驱动样式实现:
方式1:在数据中直接指定样式列
给数据添加第8列Style,通过fill-color属性设置深灰色:
const data = [ ['Task ID', 'Task Name', 'Resource', 'Start Date', 'End Date', 'Duration', 'Percent Complete', 'Style'], ['task1', '需求分析', '张三', new Date(2024, 4, 1), new Date(2024, 4, 7), null, 100, 'fill-color: #333333;'], ['task2', 'UI设计', '李四', new Date(2024, 4, 5), new Date(2024, 4, 15), null, 60, 'fill-color: #333333;'], ['task3', '后端开发', '王五', new Date(2024, 4, 12), new Date(2024, 4, 25), null, 30, 'fill-color: #333333;'], ];
方式2:通过任务类型匹配颜色
定义任务类型列,结合options.colors统一设置深灰色:
const data = [ ['Task ID', 'Task Name', 'Resource', 'Start Date', 'End Date', 'Duration', 'Percent Complete', 'Task Type'], ['task1', '需求分析', '张三', new Date(2024, 4, 1), new Date(2024, 4, 7), null, 100, 'completed'], ['task2', 'UI设计', '李四', new Date(2024, 4, 5), new Date(2024, 4, 15), null, 60, 'in-progress'], ['task3', '后端开发', '王五', new Date(2024, 4, 12), new Date(2024, 4, 25), null, 30, 'pending'], ]; const options = { height: 400, colors: ['#333333', '#333333', '#cccccc'], // 已完成/进行中设深灰,未开始设浅灰 gantt: { trackHeight: 30, }, };
内容的提问来源于stack exchange,提问作者Rogério Gouvêa
相关产品推荐
相关产品推荐

