首页 > 解决方案 > 将 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>
  );
}

标签: javascripthtmlreactjsreact-hooks

解决方案


嗨尝试以下解决方案及其工作

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;

推荐阅读