简体   繁体   English

如何在我的 React 组件中使用脚本标记呈现 Html?

[英]How can I render Html with script tag in my React Component?

I am receiving HTML with JS (which builds some graph) inside script tag in a string from API.我在来自 API 的字符串中的脚本标记内接收带有 JS(构建一些图形)的 HTML。 ie. IE。

{
   template: `
<p>Hello here is the chart!</p>

<div>
  <div id="piechart"></div>

  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

  <script type="text/javascript">
    // Load google charts
    google.charts.load('current', { 'packages': ['corechart'] });
    google.charts.setOnLoadCallback(drawChart);

    // Draw the chart and set the chart values
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work', 8],
        ['Eat', 2],
        ['TV', 4],
        ['Gym', 2],
        ['Sleep', 8]
      ]);

      // Optional; add a title and set the width and height of the chart
      var options = { 'title': 'Old Allocation', 'width': `100 % `, 'height': 300 };

      // Display the chart inside the <div> element with id="piechart"
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(data, options);
    }
  </script>
</div>
`
}

I want to render that HTML inside my React Component which looks like我想在我的 React 组件中呈现该 HTML,它看起来像

import React, { Component } from 'react'
class ChartComponent extends Component {
    render() {
        return (
            <div>
                <p>Here is the chart Component</p>

                {/* Here i want to render Html template coming from API's */}
            </div>
        )
    }
}

export default ChartComponent

How can I do that?我怎样才能做到这一点?
Or is there any way to build graphs in HTML, bringing from APIs and render inside the React Component?或者有什么方法可以在 HTML 中构建图形,从 API 中引入并在 React 组件中呈现?

One way is to use dangerouslySetInnerHTML attribute and render the string content as JS code.一种方法是使用dangerouslySetInnerHTML属性并将字符串内容呈现为JS 代码。

Like this像这样

function DevScript(props) {
  /// hardcoding the data just for demo purpose
 const devCode = `
 // Load google charts
   google.charts.load('current', { 'packages': ['corechart'] });
   google.charts.setOnLoadCallback(drawChart);

   // Draw the chart and set the chart values
   function drawChart() {
     var data = google.visualization.arrayToDataTable([
       ['Task', 'Hours per Day'],
       ['Work', 8],
       ['Eat', 2],
       ['TV', 4],
       ['Gym', 2],
       ['Sleep', 8]
     ]);

     // Optional; add a title and set the width and height of the chart
     var options = { 'title': 'Old Allocation', 'width': "100 %", 'height': 300 };

     // Display the chart inside the <div> element with id="piechart"
     var chart = new google.visualization.PieChart(document.getElementById('piechart'));
     chart.draw(data, options);
 `; 
 return (
     <script
       type="text/javascript"
       dangerouslySetInnerHTML={{ __html: devCode }}
     />
 );
}

UPDATE更新

Please find the working code-sandbox link https://codesandbox.io/embed/nice-ellis-qpw4e?fontsize=14&hidenavigation=1&theme=dark请找到工作代码沙盒链接https://codesandbox.io/embed/nice-ellis-qpw4e?fontsize=14&hidenavigation=1&theme=dark

You can use dangerouslySetInnerHTML Refer to this: https://reactjs.org/docs/dom-elements.html你可以使用dangerouslySetInnerHTML参考这个: https : //reactjs.org/docs/dom-elements.html

But beware as it's risky as suggested by the name.但请注意,正如名称所暗示的那样,它有风险。

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

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