使用 TypeScript + dhtmlx-gantt 在 Next.js 中实现

发布于:2025-05-16 ⋅ 阅读:(18) ⋅ 点赞:(0)

1. 安装依赖(确保已安装)

npm install dhtmlx-gantt

2. 创建 pages/gantt.tsx

'use client'

import { useRef, useEffect } from 'react'
import { gantt } from 'dhtmlx-gantt'
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'

interface Task {
  id: number | string
  text?: string
  start_date: string | Date
  duration: number
  progress: number
  owner?: string
  priority?: string
  parent?: number | string
}

export function ProjectGantt() {
  const ganttContainerRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (gantt && ganttContainerRef.current) {
      // 配置(可选)
      gantt.config.readonly = false

      // 初始化容器
      gantt.init(ganttContainerRef.current)

      // 定义数据
      const tasks: Task[] = [
        {
          id: 1,
          text: '项目启动',
          start_date: '2025-05-20',
          duration: 3,
          progress: 0.4,
        },
        {
          id: 2,
          text: '需求调研',
          start_date: '2025-05-23',
          duration: 5,
          progress: 0.2,
          parent: 1,
        },
        {
          id: 3,
          text: 'UI设计',
          start_date: '2025-05-25',
          duration: 4,
          progress: 0.1,
          parent: 1,
        },
      ]

      // 载入数据
      gantt.parse({ data: tasks })
    }

    // 清理
    return () => {
      if (gantt) {
        gantt.clearAll()
      }
    }
  }, [])

  return (
    <div style={{ padding: '20px' }}>
      <h2>Gantt 任务视图(TypeScript版)</h2>
      <div id="gantt_here" ref={ganttContainerRef} style={{ width: '100%', height: '600px' }}></div>
    </div>
  )
}

效果图如下
在这里插入图片描述

小结

  • 用 import { gantt } from ‘dhtmlx-gantt’
  • 定义一个 Task TypeScript 接口
  • 让 ref 指向容器元素
  • 在 useEffect 中初始化、载入数据、处理清理

网站公告

今日签到

点亮在社区的每一天
去签到