簡體   English   中英

當圖表表示為 React JSX 元素時如何清除/銷毀 Chart.js 畫布

[英]How to clear/destroy Chart.js canvas when the chart is represented as a react JSX element

我在使用 chart.js 時遇到了這個問題,其中我有一個關於特定報告的圖表。 當我將頁面切換到包含 chartjs 元素的另一個頁面並切換回來時,圖表將圖表數據點上的數據標簽顯示為“x:數字,y:數字”。 在閱讀了一些關於此的內容后,我相信這是因為當我切換回原始圖表時畫布沒有被正確重置。 我發現的使用 clear() 或 destroy() 命令的修復示例參考了圖表畫布。 示例: 銷毀chart.js 條形圖以在同一<canvas> 中重繪其他圖形但是在react 中這有點棘手。 我的問題是,如何在繪制圖形之前清除畫布。 下面是用於繪制圖形的圖表組件。

cont Chart: FunctionComponent<Props> = ({data}) => {
  const options = (): ChartOptions => ({
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      display: false
    },
    tooltips: chartTooltips,
    elements: chartElementsNoLines,
    scales: {
      xAxes: [
        {
          display: true,
          id: 'x-axis-0',
          ticks: {
            suggestedMin: minMax.min,
            suggestedMax: minMax.max,
            maxTicksLimit: 7,
            maxRotation: 0,
            fontFamily: 'Roboto, sans-serif',
            fontSize: 10,
            autoSkip: true,
            callback: value => currency(value, { precision: 0 }).format()
          },
          gridLines: {
            display: false
          }
        }
      ],
      yAxes: [
        {
          type: 'linear',
          display: false,
          ticks: {
            min: 0,
            max: maxY
          },
          id: 'y-axis-0',
          gridLines: {
            display: false
          }
        }
      ]
    }
  })

  return (
     <section>
      <div className={classes.chartContainer}>
        <HorizontalBar
          data-cy="limit-chart"
          data={data}
          options={{ ...options(), ...annotationPlugin() }}
          redraw={true}
          height={80}
        />
      </div>
     </section>
  )
}


我在重新渲染時遇到了數據和大小更改的問題,我找到了一種方法來強制更新它使用 ref ( profitChartRef.current.chartInstance.destroy(); ) 來銷毀 chartInstance,然后渲染完全反映已更新內容的全新實例

export const ProfitReportChart = () => {
    const profitChartRef = useRef();

    if (profitChartRef?.current) {
        profitChartRef.current.chartInstance.destroy();
    }

    return <Bar ref={profitChartRef} data={data} options={options} redraw/>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM