如何在反应中从数据库中呈现 HTML?
How to render HTML from database in react?
我正在借助 Grapesjs 制作自定义网页。我想在 react js 中渲染 html 页面,该页面已被 grapesjs 编辑器保存在数据库中。以下是保存数据的格式。
现在我只能在检查 window 中获取 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>;
};
你可以这样做
const App = () => {
const data = 'lorem <b>ipsum</b>';
return (
<div
dangerouslySetInnerHTML={{__html: data}}
/>
);
}
export default App;
您需要使用 useEffect
挂钩将 response.data
设置为组件 state
,然后使用 dangerouslySetInnerHTML [=20= 呈现 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"]
}}
/>
);
};
我正在借助 Grapesjs 制作自定义网页。我想在 react js 中渲染 html 页面,该页面已被 grapesjs 编辑器保存在数据库中。以下是保存数据的格式。
现在我只能在检查 window 中获取 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>;
};
你可以这样做
const App = () => {
const data = 'lorem <b>ipsum</b>';
return (
<div
dangerouslySetInnerHTML={{__html: data}}
/>
);
}
export default App;
您需要使用 useEffect
挂钩将 response.data
设置为组件 state
,然后使用 dangerouslySetInnerHTML [=20= 呈现 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"]
}}
/>
);
};