EChartComponent.js 2.3 KB
import React,{PropTypes} from 'react';
import echarts from 'echarts';
import elementResizeEvent from 'element-resize-event';



class EChartComponent extends React.Component {
	constructor (props) {
		super(props);
	}
	static propTypes={
		option: PropTypes.object.isRequired,
        notMerge: PropTypes.bool,
        lazyUpdate: PropTypes.bool,
        style: PropTypes.object,
        theme: PropTypes.string,
        onChartReady: PropTypes.func,
        showLoading: PropTypes.bool,
        onEvents: PropTypes.object
	}
	componentDidMount(){
        setTimeout(()=>{
            let echartObj = this.renderEchartDom();
            let onEvents = this.props.onEvents || [];

            for (let eventName in onEvents) {
                // ignore the event config which not satisfy
                if (typeof eventName === 'string' && typeof onEvents[eventName] === 'function') {
                    // binding event
                    echartObj.on(eventName, function(param) {onEvents[eventName](param, echartObj);});
                }
            }
            // on chart ready
            if (typeof this.props.onChartReady === 'function') this.props.onChartReady(echartObj);

            // on resize
            elementResizeEvent(this.refs.echartsDom, function() {
                echartObj.resize();
            });
        },300);
    }
    componentDidUpdate() {
        this.renderEchartDom()
    }
    componentWillUnmount() {
        echarts.dispose(this.refs.echartsDom);
    }
    renderEchartDom() {
        // init the echart object
        let echartObj = this.getEchartsInstance();
        // set the echart option
        echartObj.setOption(this.props.option, this.props.notMerge || false, this.props.lazyUpdate || false);
        // set loading mask
        if (this.props.showLoading) echartObj.showLoading();
        else echartObj.hideLoading();
        return echartObj;
    }
    getEchartsInstance() {
        // return the echart object
        return echarts.getInstanceByDom(this.refs.echartsDom) || echarts.init(this.refs.echartsDom, this.props.theme);
    }
	render(){
		let style = this.props.style || {height: '600px'}; 
        return (
            <div ref='echartsDom'
                style={style} >
                </div>
		);
	}
}


export default EChartComponent;