[英]Convert a JSX.Element to an HTMLElement
我想將這個庫用於我的 react js 項目https://www.npmjs.com/package/html-to-image 。
在我的例子中,我想使用一個包含簡單 div 的 var 並將其導出為圖像,但是有一個問題:我的 var(節點)是一個JSX.Element
並且庫的“toPng”方法接受一個參數HTMLElement
。
我知道庫的文檔建議使用這樣的方法來獲取 HTMLElement: var node = document.getElementById('my-node')
但在我的情況下我不能這樣做,因為我的節點不是在文檔中。
那么有一種方法可以將 JSX.Element 轉換為 HTMLElement 嗎? 提前致謝;)
使用renderToStaticMarkup
來做到這一點。
import { renderToStaticMarkup } from "react-dom/server"
const output = document.createElement("div")
staticElement = renderToStaticMarkup(reactElement))
output.innerHTML = `<div>${staticElement}</div>`
問題可能很老,但是在為此尋找解決方案時,我發現了一種將隱藏元素渲染為圖像的優雅方法。
render() {
return (
<div>
<div
id="image-template"
className="d-none"
style={{
width: "200px",
height: "200px",
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "white",
fontSize: "10px",
textAlign: "center",
backgroundColor: "green",
}}
>
<span style={{ margin: "20px" }}>{"Hey, an image rendered but not visible!"}</span>
</div>
</div>
);
}
使用 class d-none
(來自 bootstrap),該元素對用戶是隱藏的,因此放置它的位置無關緊要。 bootstrap 中的d-none
基本上是display: none;important;
.
現在添加一個 function 來創建一個鏡像:
async createImage() {
const template = document.getElementById("image-template").cloneNode(true);
template.classList.remove("d-none");
const base64Image = await htmlToImage.toPng(template, {
height: 200,
width: 200,
});
// Do whatever you want to do with your image
}
該元素被克隆並刪除d-none
/ display: none
以便能夠使用htmlToImage
呈現它。 結果是您可以在任何地方使用的 base64 數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.