在React 组件中使用Echarts
在完成一個(gè)需求的時(shí)候碰到一個(gè)場(chǎng)景需要使用柱狀圖。涉及到可視化,第一反應(yīng)當(dāng)然是Echarts了。平時(shí)用js加載Echarts組件很方便,但是在React中就要費(fèi)下神了。各種連蒙帶猜實(shí)現(xiàn)了。edmo里的Echarts的例子就是Echarts文檔上介紹的最簡(jiǎn)單的應(yīng)用。
render:function() {var info = 1;return ( <div className="mt15 xui-financialAnalyse-page"> <div className="xui-general"><Chart data={info} data-info={info} /></div></div> )}
這是調(diào)用Echarts組件的地方,給里面?zhèn)髁?個(gè)屬性(data-開(kāi)頭是H5定義的規(guī)范)
var Chart = React.createClass({getInitialState: function() {this.token = Store.addListener(this.onChangeData);return {}},componentWillMount: function() {var info = this.props.data; //HTML5規(guī)定自定義屬性要以data-開(kāi)頭,這樣的可以如下取console.log(this.props['data-info']) Action.getInfo(info);},componentDidUpdate: function() {
this.showChart(this.state.data)},onChangeData: function() {var data = Store.getData();this.setState({data: data['info']['data'] //后臺(tái)返回的數(shù)據(jù)});},showChart: function(dataSet){var myChart = echarts.init(document.getElementById('main'));var option = {title: {text: 'ECharts 入門(mén)示例'},color: ['#3398DB'],tooltip : {trigger: 'axis',axisPointer : { type : 'shadow' }},grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},xAxis : [{type : 'category',data : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],axisTick: {alignWithLabel: true}}],yAxis : [{type : 'value'}],series : [{name:'你好',type:'bar',barWidth: '60%',data: dataSet}]};myChart.setOption(option);},render: function() {return (<div id="main" style={{width: 500, height:500}}></div> )} });
上面是完整的demo Echarts組件的代碼,主要是利用了React根據(jù)不同狀態(tài)(3種狀態(tài))提供的處理函數(shù)(一共有5種)。
1、componentWillMount:在插入真實(shí)DOM之前發(fā)起Action,向后端請(qǐng)求數(shù)據(jù)。
2、onChangeStore:在數(shù)據(jù)變更的時(shí)候更新數(shù)據(jù),并在getInitialState中加入監(jiān)聽(tīng)Store中數(shù)據(jù)變化的監(jiān)聽(tīng)器。
3、componentDidUpdate:在數(shù)據(jù)被重新渲染之后,觸發(fā)showChart()方法繪制canvas。
4、showChart:配置Echarts,具體配置信息可以參考Echarts文檔
5、如果組件生命周期結(jié)束,那么要加上如下代碼:
componentWillUnmount: function() {this.token.remove();},否則會(huì)報(bào)錯(cuò):?Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.?
?
最后附上效果圖:
轉(zhuǎn)載于:https://www.cnblogs.com/youyouluo/p/5981493.html
總結(jié)
以上是生活随笔為你收集整理的在React 组件中使用Echarts的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: webform(九)——JQuery基础
- 下一篇: jQuery Layer 弹层组件