在React中使用渲染原始HTML源代码不会显示源代码的主体样式

时间:2018-12-18 14:54:55

标签: html reactjs

为了在React中渲染一些HTML源代码,我使用dangerouslysetinnerhtml

问题,Html源的样式不像我们预期的那样显示。

例如:假设我们有这个;

<!DOCTYPE html>
<html>
<body bgcolor='#E6E6FA'>
<h1>Hello world!</h1>
<p><a href='https://www.w3schools.com'>Visit W3Schools.com!</a></p>
<p>The bgcolor attribute is not supported in HTML5. Use CSS instead.</p>
</body>
</html>

当我尝试呈现此html代码时,bgcolor并未如我们预期的那样显示。

demo

demo 2

2 个答案:

答案 0 :(得分:1)

我确实能够看到“ 演示2 ”示例中的bgcolor在起作用。

但是,为了获得良好的做法,您应该通过专用的样式元素(<style></style>)来应用CSS样式,如下所示:

<head><style>body{background-color: #E6E6FA;}</style></head>

因此,示例代码的一个有效示例为:

import React from "react";
import { render } from "react-dom";

const htmlString =
  "<!DOCTYPE html><html><head><style>body{background-color:#E6E6FA;}</style></head><body><h1>Hel1lo world!</h1><p><a href='https://www.w3schools.com'>Visit W3Schools.com!</a></p><p>The bgcolor attribute is not supported in HTML5. Use CSS instead.</p></body></html>";

const App = () => <div dangerouslySetInnerHTML={{ __html: htmlString }} />;

render(<App />, document.getElementById("root"));

https://codesandbox.io/s/1q0781w5ml

答案 1 :(得分:1)

“根” 已经在已呈现的页面(而不是空白页面)的文档主体中。因此,您是在已经有HEAD等内容的页面内呈现新页面。

您可能要根据目标将其更改为在iframe中呈现。

相关问题