• 在React 组件中使用Echarts


      在完成一个需求的时候碰到一个场景需要使用柱状图。涉及到可视化,第一反应当然是Echarts了。平时用js加载Echarts组件很方便,但是在React中就要费下神了。各种连蒙带猜实现了。edmo里的Echarts的例子就是Echarts文档上介绍的最简单的应用。

      

    render:function() {
            
        var info = 1;
    
            return (    
                <div className="mt15 xui-financialAnalyse-page">     
                    <div className="xui-general">
                        <Chart data={info} data-info={info} />
                    </div>
                </div>
            )
        }

      这是调用Echarts组件的地方,给里面传了2个属性(data-开头是H5定义的规范)

      

    var Chart = React.createClass({
        getInitialState: function() {
            this.token = Store.addListener(this.onChangeData);
            return {}
        },
    
        componentWillMount: function() {
            var info = this.props.data; 
            //HTML5规定自定义属性要以data-开头,这样的可以如下取
            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'] //后台返回的数据 }); }, showChart: function(dataSet){ var myChart = echarts.init(document.getElementById('main')); var option = { title: { text: 'ECharts 入门示例' }, 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={{ 500, height:500}}></div> ) } });

      上面是完整的demo Echarts组件的代码,主要是利用了React根据不同状态(3种状态)提供的处理函数(一共有5种)。

      1、componentWillMount:在插入真实DOM之前发起Action,向后端请求数据。

      2、onChangeStore:在数据变更的时候更新数据,并在getInitialState中加入监听Store中数据变化的监听器。

      3、componentDidUpdate:在数据被重新渲染之后,触发showChart()方法绘制canvas。

      4、showChart:配置Echarts,具体配置信息可以参考Echarts文档

      5、如果组件生命周期结束,那么要加上如下代码:

        componentWillUnmount: function() {
            this.token.remove();
        },

      否则会报错: 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. 

      最后附上效果图:

        

      

  • 相关阅读:
    [考试反思]0421省选模拟76:学傻
    [考试反思]0420省选模拟75:安在
    [考试反思]0418省选模拟74:杂枝
    [考试反思]0417省选模拟73:纠结
    [考试反思]0416省选模拟72:停滞
    [考试反思]0415省选模拟71:限制
    [考试反思]0414省选模拟70:阻塞
    [考试反思]0413省选模拟69:遗弃
    [考试反思]0411省选模拟68:毒瘤
    [考试反思]0410省选模拟67:迷惑
  • 原文地址:https://www.cnblogs.com/youyouluo/p/5981493.html
Copyright © 2020-2023  润新知