【发布时间】:2021-08-03 07:41:20
【问题描述】:
我正在尝试从组件中获取 HTML 作为标记字符串,因此我可以将其附加到文本区域。下面带有第一个按钮的 hack 有效,但我认为这不是解决此问题的正确方法,而且我不喜欢在我的页面中有一个随机隐藏的 div。
.renderToStaticMarkup 看似完美的工具,却直接报错:
Uncaught TypeError: can't access property "blockList", Object(...)(...) is null
blocklist 来自商店,难道 .renderToStaticMarkup 不能使用 useContext 钩子在组件上调用吗?
import React, { useState, useEffect } from "react";
import ReactDOMServer from "react-dom";
import { Icon, BlockCompilerToHTML } from "components/lib";
import Style from "./themeConfigCard.module.scss";
import { MyButton } from "components/myButton/myButton";
export function ThemeConfigCard(props) {
let htmlString = "";
useEffect(() => {
//htmlString = ReactDOMServer.renderToStaticMarkup(<BlockCompilerToHTML />);
//Above commented because it trows error.
}, []);
return (
<div className={Style.themeConfigCard}>
<MyButton
onClick={() => {
console.log(document.getElementById("rendered_html").innerHTML);
document.getElementById("mytextarea").value =
document.getElementById("rendered_html").innerHTML;
}}
>
Get HTML as string with hack
</MyButton>
<MyButton
onClick={() => {
document.getElementById("mytextarea").value = htmlString;
}}
>
Get HTML as string using renderToStaticMarkup
</MyButton>
<textarea id="mytextarea"></textarea>
<div style={{ display: "none" }} id="rendered_html">
<BlockCompilerToHTML />
</div>
</div>
);
}
【问题讨论】:
-
尝试使用 setState 来存储 htmlString。也许它应该工作?
-
@Zeeshan 似乎没有解决我的问题。我认为它与
<BlockCompilerToHTML />中的“useContext”有一些关系@
标签: javascript html reactjs react-hooks