javascript - 将 REACT 组件渲染为 HTML 字符串以复制或添加到 textarea
问题描述
我正在尝试从组件中获取 HTML 作为标记字符串,因此我可以将其附加到文本区域。下面第一个按钮的 hack 有效,但我认为这不是解决这个问题的正确方法,我不喜欢在我的页面中有一个随机隐藏的 div。
.renderToStaticMarkup似乎是完美的工具,但它直接引发错误:
未捕获的 TypeError:无法访问属性“blockList”,Object(...)(...) 为 null
blocklist 来自商店,是否无法使用 useContext 挂钩在组件上调用 .renderToStaticMarkup ?
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>
);
}
解决方案
嗨尝试以下解决方案及其工作
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server'
class App extends React.Component {
state = {};
render(){
const {textarea} = this.state;
return (
<div>
<textarea id="mytextarea"></textarea>
<Test />
<button onClick={this.handleClick} >Set textarea</button>
</div>
)
}
handleClick = ()=>{
const value = renderToStaticMarkup(<Test />);
document.getElementById("mytextarea").value = value;
}
}
const Test = ()=>{
return (
<div>Hello</div>
)
}
export default App;
推荐阅读
- symfony4 - fosjsrouting 转储不正确的路径
- python - 跨索引数组获取最小值
- python-3.x - Python 程序在启动时在 tmux 会话中运行时崩溃
- c - 为什么某些预处理器宏不扩展,除非它们是另一个宏的参数?
- android - ViewPager2 fragments overlap tabbed items
- c++ - vkCreateSwapchainKHR():未检索到此物理设备的表面功能
- python - 类型错误:join() 参数必须是 str 或 bytes,而不是 'list'
- python - 用 yum 安装 python-devel
- reactjs - 胜利本机:使用胜利条形图时,事件道具在本机反应中不起作用/事件在本机反应中未触发
- android - 此应用无权使用 Firebase 身份验证。请确认在 Firebase 中配置了正确的包名称和 SHA-1