【问题标题】:How to render HTML from database in react?如何在反应中从数据库中呈现 HTML?
【发布时间】:2022-02-03 13:08:24
【问题描述】:

我正在 Grapesjs 的帮助下制作自定义网页。我想在react js中渲染html页面,该页面已由grapesjs编辑器保存在数据库中。以下是保存数据的格式。

现在我只能在检查窗口中获取 html 代码,但是如何在页面上呈现它?

import React from "react";
import axios from "axios";
// import {renderWebpage} from "../actions/webpage"

export const Page: React.FC = () => {
  const renderWebpage = axios
    .get("http://localhost:8080/61ea7fd2268f37443ca4d59a")
    .then((response) => {
      console.log("response", response);
      console.log(response.data, "data");
    });

  return <div>demo</div>;
};

【问题讨论】:

    标签: javascript html reactjs grapesjs


    【解决方案1】:

    你可以这样做

    const App = () => {
      const data = 'lorem <b>ipsum</b>';
    
      return (
        <div
          dangerouslySetInnerHTML={{__html: data}}
        />
      );
    }
    
    export default App;
    

    【讨论】:

      【解决方案2】:

      您需要使用useEffect 挂钩将response.data 设置为组件state,然后使用dangerouslySetInnerHTML 属性呈现HTML 字符串。

      尝试如下。

      import React, { useState, useEffect } from "react";
      import axios from "axios";
      // import {renderWebpage} from "../actions/webpage"
      type HTMLData = {
        content: { "mycustom-html": string };
      };
      
      export const Page: React.FC = () => {
        const [htmlData, setHtmlData] = useState<HTMLData>({
          content: { "mycustom-html": "<p>demo</p>" }
        });
      
        const renderWebpage = () => {
          axios
            .get("http://localhost:8080/61ea7fd2268f37443ca4d59a")
            .then((response) => {
              console.log("response", response);
              console.log(response.data, "data");
              setHtmlData(response.data);
            });
        };
      
        useEffect(() => {
          renderWebpage();
        }, []);
      
        return (
          <div
            dangerouslySetInnerHTML={{
              __html: htmlData?.content?.["mycustom-html"]
            }}
          />
        );
      };
      

      【讨论】:

        猜你喜欢
        • 2020-03-18
        • 1970-01-01
        • 2016-12-04
        • 2019-05-13
        • 2011-11-26
        • 2021-04-11
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多