Skip to content

方法 (Methods)

通过 ref 可以调用 GanttFlow 的各种方法。

获取 Ref

tsx
const ganttRef = useRef(null)

// 调用方法
ganttRef.current?.方法名()

导出方法

exportAsPNG

导出甘特图为 PNG 图片。

typescript
exportAsPNG(options?: ExportOptions): Promise<string>

返回值: 返回图片的 data URL

tsx
const handleExportPNG = async () => {
  try {
    const dataUrl = await ganttRef.current?.exportAsPNG({
      scale: 2,
      padding: 20,
      backgroundColor: '#ffffff'
    })
    console.log('PNG data URL:', dataUrl)
    
    // 下载
    const link = document.createElement('a')
    link.href = dataUrl
    link.download = 'gantt.png'
    link.click()
  } catch (error) {
    console.error('导出失败:', error)
  }
}

exportAsPDF

导出甘特图为 PDF 文件。

typescript
exportAsPDF(options?: ExportOptions): Promise<Blob>

返回值: 返回 PDF 的 Blob 对象

tsx
const handleExportPDF = async () => {
  try {
    const blob = await ganttRef.current?.exportAsPDF({
      scale: 2,
      padding: 20
    })
    
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'gantt.pdf'
    link.click()
    URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

exportAsExcel

导出为 Excel 文件。

typescript
exportAsExcel(options?: ExportOptions): Promise<Blob>

返回值: 返回 Excel 的 Blob 对象

tsx
const handleExportExcel = async () => {
  try {
    const blob = await ganttRef.current?.exportAsExcel({
      includeDependencies: true,
      includeProgress: true,
      dateFormat: 'YYYY-MM-DD'
    })
    
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'gantt.xlsx'
    link.click()
    URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

视图控制

setViewMode

切换视图模式。

typescript
setViewMode(mode: ViewMode): void
tsx
ganttRef.current?.setViewMode('day')
ganttRef.current?.setViewMode('week')
ganttRef.current?.setViewMode('month')
ganttRef.current?.setViewMode('quarter')
ganttRef.current?.setViewMode('year')

getViewMode

获取当前视图模式。

typescript
getViewMode(): ViewMode
tsx
const currentMode = ganttRef.current?.getViewMode()
console.log('当前视图:', currentMode)

scrollToTask

滚动到指定任务。

typescript
scrollToTask(taskId: string, options?: ScrollOptions): void
tsx
// 滚动到任务
ganttRef.current?.scrollToTask('task-123')

// 带动画滚动到任务
ganttRef.current?.scrollToTask('task-123', { smooth: true })

scrollToDate

滚动到指定日期。

typescript
scrollToDate(date: Date, options?: ScrollOptions): void
tsx
ganttRef.current?.scrollToDate(new Date('2024-03-15'))

fitToScreen

自动适应屏幕。

typescript
fitToScreen(): void
tsx
ganttRef.current?.fitToScreen()

zoomIn

放大视图。

typescript
zoomIn(): void

zoomOut

缩小视图。

typescript
zoomOut(): void

setZoom

设置缩放级别。

typescript
setZoom(level: number): void
// level: 0.5 - 2.0
tsx
ganttRef.current?.setZoom(1.5)  // 放大 150%

数据操作

getVisibleTasks

获取当前可见的任务列表。

typescript
getVisibleTasks(): Task[]
tsx
const visibleTasks = ganttRef.current?.getVisibleTasks()
console.log('可见任务:', visibleTasks.length)

getAllTasks

获取所有任务。

typescript
getAllTasks(): Task[]

addTask

添加新任务。

typescript
addTask(task: Task): void
tsx
ganttRef.current?.addTask({
  id: 'new-task',
  name: '新任务',
  start: '2024-03-01',
  end: '2024-03-05',
  progress: 0
})

removeTask

删除任务。

typescript
removeTask(taskId: string): void
tsx
ganttRef.current?.removeTask('task-123')

updateTask

更新任务信息。

typescript
updateTask(taskId: string, updates: Partial<Task>): void
tsx
ganttRef.current?.updateTask('task-123', {
  name: '更新后的名称',
  progress: 50,
  start: '2024-03-02',
  end: '2024-03-08'
})

getTask

获取单个任务。

typescript
getTask(taskId: string): Task | undefined
tsx
const task = ganttRef.current?.getTask('task-123')
console.log('任务详情:', task)

addDependency

添加依赖关系。

typescript
addDependency(dependency: Dependency): boolean
// 返回是否添加成功(循环依赖会失败)
tsx
const success = ganttRef.current?.addDependency({
  fromId: 'task-1',
  toId: 'task-2',
  type: 'finish_to_start'
})
if (!success) {
  console.error('添加依赖失败,可能存在循环依赖')
}

removeDependency

删除依赖关系。

typescript
removeDependency(fromId: string, toId: string): void
tsx
ganttRef.current?.removeDependency('task-1', 'task-2')

主题控制

toggleTheme

切换亮色/暗色主题。

typescript
toggleTheme(): void
tsx
<button onClick={() => ganttRef.current?.toggleTheme()}>
  切换主题
</button>

setTheme

设置指定主题。

typescript
setTheme(theme: 'light' | 'dark' | 'auto'): void
tsx
ganttRef.current?.setTheme('dark')

getTheme

获取当前主题。

typescript
getTheme(): 'light' | 'dark'

历史记录

undo

撤销上一步操作。

typescript
undo(): boolean
// 返回是否撤销成功

redo

重做上一步操作。

typescript
redo(): boolean
// 返回是否重做成功

canUndo

是否可以撤销。

typescript
canUndo(): boolean

canRedo

是否可以重做。

typescript
canRedo(): boolean

clearHistory

清除历史记录。

typescript
clearHistory(): void
tsx
<div className="toolbar">
  <button 
    onClick={() => ganttRef.current?.undo()}
    disabled={!ganttRef.current?.canUndo()}
  >
    撤销
  </button>
  <button 
    onClick={() => ganttRef.current?.redo()}
    disabled={!ganttRef.current?.canRedo()}
  >
    重做
  </button>
</div>

关键路径

isOnCriticalPath

检查任务是否在关键路径上。

typescript
isOnCriticalPath(taskId: string): boolean
tsx
const isCritical = ganttRef.current?.isOnCriticalPath('task-123')
console.log('是否在关键路径上:', isCritical)

getCriticalPath

获取关键路径上的所有任务。

typescript
getCriticalPath(): Task[]

选中操作

selectTask

选中指定任务。

typescript
selectTask(taskId: string): void

deselectTask

取消选中指定任务。

typescript
deselectTask(taskId: string): void

clearSelection

清除所有选中。

typescript
clearSelection(): void

getSelectedTasks

获取所有选中的任务。

typescript
getSelectedTasks(): Task[]

内部实例

getInstanceCore

获取 GanttChart 核心实例,用于高级操作和事件监听。

typescript
getInstanceCore(): GanttChartCore | null
tsx
const core = ganttRef.current?.getInstanceCore()
// 访问内部方法
core?.on('custom:event', handler)
core?.emit('custom:event', data)

工具方法

getStats

获取甘特图统计信息。

typescript
getStats(): GanttStats
typescript
interface GanttStats {
  totalTasks: number
  completedTasks: number
  inProgressTasks: number
  overdueTasks: number
  totalProgress: number
  startDate: Date
  endDate: Date
  duration: number  // 天数
}
tsx
const stats = ganttRef.current?.getStats()
console.log('总任务:', stats.totalTasks)
console.log('完成:', stats.completedTasks)
console.log('逾期:', stats.overdueTasks)

refresh

刷新甘特图。

typescript
refresh(): void

destroy

销毁甘特图实例。

typescript
destroy(): void

相关链接

基于 MIT 许可证发布