[英]React export component that is not diplayed to PNG
我正在尝试将图表导出到图像,并且我希望图表图像具有未显示在屏幕上的自定义图例。
我怎样才能做到这一点?
现在我尝试使用react-component-export-image 导出,但如果未显示组件,则参考为 null 并且无法导出。 请参阅组件导出实现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
这将完成这项工作。 如果您需要进一步的支持,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.