React 应用程序收到了一个可视化代码,我使用 unescape 函数来获取字符串中的 HTML 代码。该字符串有一个div
带有可视化 id 的script
标签和包含用于生成可视化的 javascript 的标签。
import React from "react";
import parse from "html-react-parser";
export default function App() {
// This code is received from the backend
const vizCode =
"%3Cdiv%20id%3D'chartdiv_1614071920146'%3E%3C%2Fdiv%3E%3Cscript%20type%3D'text%2Fjavascript'%3E%20var%20width_1614071920146%20%3D%20700%3Bvar%20height_1614071920146%20%3D%20700%3Bvar%20chart_1614071920146%20%3D%20c3.generate(%7Bbindto%3A%20'%23chartdiv_1614071920146'%2C%20size%3A%20%7B%20width%3A%20(width_1614071920146%20-%2020)%2C%20height%3A%20(height_1614071920146%20-%2020)%20%7D%2C%20data%3A%20%7Bcolumns%3A%20%5B%20%5B'%20'%2C%201.0%2C%201.0%2C%203.0%2C%205.0%2C%205.0%5D%20%5D%2C%20type%3A%20'spline'%7D%2C%20legend%3A%20%7Bshow%3Afalse%7D%2C%20axis%3A%20%7B%20x%3A%20%7B%20type%3A%20'category'%2C%20categories%3A%20%5B'New%20Course'%2C'group%20course%201'%2C'Testkurs%20'%2C'test_course'%2C'Moodle4CollaborativeMOOCs'%5D%20%7D%20%7D%7D)%3B%3C%2Fscript%3E";
const unescapedVizCode = unescape(vizCode);
console.log(unescapedVizCode);
// Output -> <div id='chartdiv_1614071920146'></div><script type='text/javascript'> var width_1614071920146 = 700;var height_1614071920146 = 700;var chart_1614071920146 = c3.generate({bindto: '#chartdiv_1614071920146', size: { width: (width_1614071920146 - 20), height: (height_1614071920146 - 20) }, data: {columns: [ [' ', 1.0, 1.0, 3.0, 5.0, 5.0] ], type: 'spline'}, legend: {show:false}, axis: { x: { type: 'category', categories: ['New Course','group course 1','Testkurs ','test_course','Moodle4CollaborativeMOOCs'] } }});</script>
let objectData = parse(unescapedVizCode);
let divData = objectData[0];
let scriptData = objectData[1].props.dangerouslySetInnerHTML.__html;
return (
<div className="App">
{objectData}
</div>
);
}
在这里,我提供了代码框链接
我用dangerouslySetInnerHtml
来显示可视化但无法可视化图表。我在公共文件夹中添加了一个 test.html 以在浏览器中显示可视化。任何帮助深表感谢。