未显示为 PNG 的 React 导出组件

问题描述

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

我该怎么做?

目前我尝试使用 react-component-export-image 导出,但如果未显示组件,则 ref 为空且无法导出。请参阅组件导出实现 src-code

我当前代码的示例:codesandbox

解决方法

您可以通过在渲染之前操作画布来实现这一目标的唯一方法。您可以通过在 onclone 中设置 html2CanvasOptions 选项来实现。

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

这将完成工作。如果您需要进一步的支持,请告诉我。