我有这样的东西
public render(){
let htmlRender = "<html><body><h2>Children</h2>Joe has three kids:<br/><ul><li>Linn Fenimore Cooper Cary (married writer <a href='Ved Mehta'>Ved Mehta</a> in 1983)</li><li>kid2</li><li>kid3</li></ul></body></html>";
const doc = new DOMParser().parseFromString(htmlRender,'text/html');
let ele = doc.evaluate("/html/body/ul/li[1]/a[1]", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
ele.singleNodeValue.style.background = 'pink';
return (
<div className="details-block context-block">
<h5>Context</h5>
<div dangerouslySetInnerHTML={{__html:doc.body.toString()}} /> --> This returns [object HTMLBodyElement]
</div>
);
}
这就是我上面所做的 - 将 html 字符串转换为 HTML 对象。然后使用 Xpath 解析它。操纵它(添加颜色)然后我想显示它。但它显示为 [object HTMLBodyElement]
。我做错了什么?
感谢您的帮助!
最佳答案
我在 Chrome 的控制台中尝试过,我认为您的问题是 doc.body.toString()
.
> let x = "<html>...</html>";
> let y = new DOMParser().parseFromString(x, "text/html");
> y // #document
> y.body // <body>…</body>
> y.body.toString() // "[object HTMLBodyElement]"
而不是 toString()
,使用innerHTML
(如果您想要 <body/>
标签,则可以使用outerHTML)。
> y.body.innerHTML // "<h2>Children</h2> ..."
发生的事情是你正在创建一个 React div
具有文字字符串内容“[object HTMLBodyElement]”的元素,而不是 doc.body
的内容-doc.body.innerHTML
编辑:根据评论here你实际上应该使用 new XMLSerializer().serializeToString(document)
- 由你决定;任何有效的方法。
关于javascript - 如何在 React 渲染中渲染 HTMLDocument 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42913318/