未显示为 PNG 的 React 导出组件

React export component that is not diplayed to PNG

我正在尝试将图表导出为图像,我希望图表图像具有未显示在屏幕上的自定义图例。

我该怎么做?

目前我尝试使用 react-component-export-image but if the component is not displayed the ref is null and It cannot be exported. See component export implementation src-code 导出。

我当前的代码示例:codesandbox

您可以通过在渲染前操纵 canvas 来实现此目的的唯一方法。您可以通过在 html2CanvasOptions.

中设置 onclone 选项来做到这一点
import { Line } from "react-chartjs-2";
import { exportComponentAsPNG } from "react-component-export-image";
import React, { useRef } from "react";
import { data } from "./data";

const Chart = React.forwardRef((props, ref) => {
  return (
    <div ref={ref} style={{ maxWidth: "800px" }}>
      <Line data={data} height={80} />
      <div id="legend" style={{ textAlign: "center", visibility: "hidden" }}>
        Legend
      </div> {/* Visibility set to hidden using css */}
    </div>
  );
});

const App = () => {
  const componentRef = useRef();

  return (
    <React.Fragment>
      <Chart ref={componentRef} />
      <button
        style={{ margin: "30px" }}
        onClick={() => exportComponentAsPNG(componentRef, {
            html2CanvasOptions: {
              onclone: (clonedDoc) => {
                clonedDoc.getElementById("legend").style.visibility = "visible";
                // Visibility set to visible using `onclone` method
              },
            },
          })
        }
      >
        Export As PNG
      </button>
    </React.Fragment>
  );
};

export default App;

https://codesandbox.io/s/export-chart-821kc?file=/src/App.js

这样就可以了。如果您需要进一步的支持,请告诉我。