[英]Convert a JSX.Element to an HTMLElement
I want to use this library for my react js project https://www.npmjs.com/package/html-to-image .我想将这个库用于我的 react js 项目https://www.npmjs.com/package/html-to-image 。
In my case I want to use a var that contain a simple div and export It as an Image, but there's a problem: my var (node) is a JSX.Element
and the "toPng" method of the library accept as a parameter an HTMLElement
.在我的例子中,我想使用一个包含简单 div 的 var 并将其导出为图像,但是有一个问题:我的 var(节点)是一个
JSX.Element
并且库的“toPng”方法接受一个参数HTMLElement
。
I know that the doc of the library suggests to use methods like this to get an HTMLElement: var node = document.getElementById('my-node')
but in my case I can't do something like this because my node isn't in the document.我知道库的文档建议使用这样的方法来获取 HTMLElement:
var node = document.getElementById('my-node')
但在我的情况下我不能这样做,因为我的节点不是在文档中。
So there's a way to convert a JSX.Element to an HTMLElement?那么有一种方法可以将 JSX.Element 转换为 HTMLElement 吗? Thanks in advance;)
提前致谢;)
Use renderToStaticMarkup
to do so.使用
renderToStaticMarkup
来做到这一点。
import { renderToStaticMarkup } from "react-dom/server"
const output = document.createElement("div")
staticElement = renderToStaticMarkup(reactElement))
output.innerHTML = `<div>${staticElement}</div>`
Question might be old, but while looking for a solution for this I found an elegant way to render a hidden element as an image.问题可能很老,但是在为此寻找解决方案时,我发现了一种将隐藏元素渲染为图像的优雅方法。
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>
);
}
With the class d-none
(from bootstrap) the element is hidden to the user, so it does not matter where you place it.使用 class
d-none
(来自 bootstrap),该元素对用户是隐藏的,因此放置它的位置无关紧要。 d-none
in bootstrap is basically display: none;important;
bootstrap 中的
d-none
基本上是display: none;important;
. .
Now add a function to create an image:现在添加一个 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
}
The element is cloned and the d-none
/ display: none
removed to be able to render it with htmlToImage
.该元素被克隆并删除
d-none
/ display: none
以便能够使用htmlToImage
呈现它。 The result is the base64 data you can use whereever you want.结果是您可以在任何地方使用的 base64 数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.