Javascript 在ReactJS中使用Google图表
我正在尝试在ReactJS应用程序中使用google图表。我不想使用“”。 我已经搜索了整个互联网,这是我目前的代码。。。 在我的Javascript 在ReactJS中使用Google图表,javascript,reactjs,charts,Javascript,Reactjs,Charts,我正在尝试在ReactJS应用程序中使用google图表。我不想使用“”。 我已经搜索了整个互联网,这是我目前的代码。。。 在我的index.html中,我执行以下操作: <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="https://www.google.com/j
index.html
中,我执行以下操作:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload=
{'modules':[{'name':'visualization','version':'1.1','packages':
['corechart']}]}"></script>
在react中,了解组件生命周期是您最需要的一件事。例如,在jQuery中,我们使用
ready
函数来了解DOM何时已完全加载。在react中,等价物为componentDidMount
因此,您可以在componentDidMount中声明setOnLoadCallback
另外,记住在构造函数中声明方法并绑定this
注意:您也可以在componentWillMount中执行类似操作(update>>componentWillMount已被弃用),但在这种情况下,它将抛出一个错误,因为此时尚未加载div表_div
iethis.renderGoogleTable=this.renderGoogleTable.bind(this)
您可以在此处阅读有关组件生命周期的更多信息:您可以将
此
作为参数传递给renderGoogleTable
或bind
函数。
import React from 'react';
import {MainViewHeader} from './MainViewHeader';
import TouristService from '../../services/TouristService';
import Util from '../../services/Util';
google.charts.load('current', {'packages':['corechart']});
export class MainView extends React.Component {
constructor() {
super();
this.state = {
touristInfos: [],
touristInfosHeader: []
};
google.charts.setOnLoadCallback(() => this.renderGoogleTable());
}
componentDidMount() {
let touristInfos = TouristService.getAllTouristInfos();
touristInfos.then(
info =>
this.setState({
touristInfos: Util.getResults(info)
})
);
//this.renderGoogleTable();
}
componentDidUpdate(){
this.renderGoogleTable();
}
renderGoogleTable(){
let data = google.visualization.arrayToDataTable(this.state.touristInfos);
let table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
render() {
return (
<div className="search-and-overview">
<MainViewHeader />
<div className="mid-region">
<div className="content">
<div className="problem-list">
<div id="table_div"></div>
</div>
</div>
</div>
</div>
);
}
}
MainView.js:36 Uncaught (in promise) TypeError: google.visualization.Table is not a constructor
at MainView.renderGoogleTable (MainView.js:36)
at MainView.js:15
at <anonymous>