简体   繁体   English

使用危险的SetInnerHTML在React中插入完整的HTML

[英]Inserting complete HTML in React using dangerouslySetInnerHTML

I have seen an example like on how to use dangerouslySetInnerHTML() .我看过一个例子,比如如何使用dangerouslySetInnerHTML()

Here inside the div we are putting some tag (anchor-tag in current example), but I need to insert complete HTML.在 div 中,我们放置了一些标签(在当前示例中为锚标签),但我需要插入完整的 HTML。

Below is the response I am getting via API;以下是我通过 API 得到的响应;

<HTML>
<HEAD>
<BODY>
....
</BODY>
</HEAD>
</HTML>

I already have React Component and corresponding HTML element gets created but after click on the button I would receive above HTML response which will have complete HTML tags ie HTML tag, body tag etc (it is making some sort of graph).我已经有了 React 组件,并且创建了相应的 HTML 元素,但是在单击按钮后,我会收到上面的 HTML 响应,其中将包含完整的 HTML 标签,即 HTML 标签、body 标签等(它正在制作某种图形)。

So, I need to Insert this newly HTML response with the existing HTML.所以,我需要用现有的 HTML 插入这个新的 HTML 响应。

You could use an iframe to show the document.您可以使用 iframe 来显示文档。 So, if you're fetching the data in an App component, for instance, you could do like this:因此,例如,如果您在App组件中获取数据,您可以这样做:

const App = () => {

  ... data fetching

  return (
    <iframe src={data} />
  );
}

where the data variable is the data you have fetched from your API endpoint.其中data变量是您从 API 端点获取的数据。

I have solved the issue using 'dangerouslySetInnerHTML'.我已经使用 'dangerouslySetInnerHTML' 解决了这个问题。 The problem I was facing is that i was having the < script > tag as well.我面临的问题是我也有 < script > 标签。 So, first I need to remove all the script tag and then again assign it.所以,首先我需要删除所有脚本标签,然后再次分配它。

 let count = (htmlDataString.toLowerCase().match(/<script/g) || []).length;
 const extractedScriptArray = [];

      for( let i= 0 ; i< count; i++){
        let extractScript = /<script\b[^>]*>([\s\S]*?)<\/script>/gm.exec(x);
        x = x.replace(extractScript[0], "");
        extractedScriptArray.push(extractScript[1]);
      }

      this.setState({ htmlData: x }, () => {
        for (let i = 0; i < count; i++) {
          window.eval(extractedScriptArray[i]);
        }
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM