Как я могу отрисовать Html с тегом script в моем React Component? - PullRequest
0 голосов
/ 13 февраля 2020

Я получаю HTML с JS (который строит некоторый график) внутри тега script в строке из API. 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>
`
}

Я хочу отобразить этот HTML внутри моего React Component, который выглядит как

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

Как я могу это сделать?
Или есть ли способ построить графики в HTML, используя API и рендеринг внутри компонента React?

Ответы [ 2 ]

0 голосов
/ 13 февраля 2020

Вы можете использовать dangerouslySetInnerHTML Обратитесь к этому: https://reactjs.org/docs/dom-elements.html

Но будьте осторожны, так как это рискованно, как следует из названия.

0 голосов
/ 13 февраля 2020

Одним из способов является использование атрибута dangerouslySetInnerHTML и отображение содержимого строки в виде кода JS.

Как это

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 }}
     />
 );
}

ОБНОВЛЕНИЕ

Пожалуйста, найдите рабочую ссылку код песочницы https://codesandbox.io/embed/nice-ellis-qpw4e?fontsize=14&hidenavigation=1&theme=dark

...