[英]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.