简体   繁体   English

Kendo React 将图表保存为图像

[英]Kendo React save chart as image

I'm having a problem about the download of the kendo react chart as an image,我在下载剑道反应图表作为图像时遇到问题,
currently the download works but only for my latest chart (I have six of them)目前下载有效,但仅适用于我的最新图表(我有六个)
I've recreated the error in stackblitz我在stackblitz中重新创建了错误
As you can see whenever I try to download one of the 2 charts the downloaded one is always the latest one正如您所看到的,每当我尝试下载 2 个图表之一时,下载的图表始终是最新的
Is there any way for fixing this?有什么办法可以解决这个问题吗?

The problem is that refContainer is being set twice inside your App component in the example you linked.问题是refContainer在您链接的示例中在您的App组件中设置了两次。 One time for each of your charts.每个图表一次。 The reference will always refer to the second chart, because the second chart overwrites the value of refContainer last.引用将始终引用第二个图表,因为第二个图表最后覆盖了refContainer的值。

What you can do instead is to create a CustomChart component that holds its own ref ( refContainer ).您可以做的是创建一个CustomChart组件,该组件拥有自己的 ref ( refContainer )。 This way you can render multiple instances of this component, without the refs clashing.这样,您可以渲染该组件的多个实例,而不会发生 refs 冲突。 This also allows us to get rid of some duplicate code for creating the chart.这也使我们能够摆脱一些用于创建图表的重复代码。

So you can do something like this:所以你可以做这样的事情:

import * as React from "react";
import {
  Chart,
  ChartSeries,
  ChartSeriesItem,
  ChartCategoryAxis,
  ChartCategoryAxisItem,
  exportVisual,
} from "@progress/kendo-react-charts";

import { exportImage } from "@progress/kendo-drawing";
import { saveAs } from "@progress/kendo-file-saver";

const CustomChart = ({ categories, data }) => {
  let refContainer = React.useRef(null);

  const onExportVisual = () => {
    const chartVisual = exportVisual(refContainer);
    if (chartVisual) {
      exportImage(chartVisual).then((dataURI) => saveAs(dataURI, "chart.png"));
    }
  };

  return (
    <>
      <button onClick={() => onExportVisual()}>Export as visual element</button>
      <Chart ref={(chart) => (refContainer = chart)}>
        <ChartCategoryAxis>
          <ChartCategoryAxisItem categories={categories} />
        </ChartCategoryAxis>
        <ChartSeries>
          <ChartSeriesItem data={data} />
        </ChartSeries>
      </Chart>
    </>
  );
};

const App = () => {
  return (
    <div>
      <CustomChart
        categories={[2015, 2016, 2017, 2018]}
        data={[10, 100, 100, 10]}
      />
      <CustomChart
        categories={[2015, 2016, 2017, 2018]}
        data={[100, 10, 10, 100]}
      />
    </div>
  );
};

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM