react+antd 中使用echarts封装组件
下载依赖包
npm install echarts --save
封装组件
import React,{ Component } from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/pie'; // 如需饼图需要在此引入饼图 ,同理其他类型图形需引入其他类型 ,如需世界地图,可引入 'echarts/map/js/world'
import 'echarts/lib/component/tooltip'; // 如有时发现option里面的某些配置项不起作用,需在此处引入
import 'echarts/lib/component/legend';
class EchartsTest extends Component {
constructor(props) {
super(props);
let id = ('_' + Math.random()).replace('.','_');
this.state = {
chartId: 'chart' + id
}
}
componentDidMount() {
this.initChart(this.state.chartId)
}
initChart(id) {
let myChart = echarts.getInstanceByDom(document.getElementById(id));
if (myChart == undefined) {
myChart = echarts.init(document.getElementById(id));
}
myChart.setOption(this.props.option,true) // this.props.option 为父组件传的option配置 或者在此定义option配置
}
componentDidUpdate() {
this.initChart(this.state.chartId);
}
render() {
const height = this.props.height;
const width = this.props.width ? this.props.width:'98%';
return (
<div id={this.state.chartId} style={{width: width, height: height}} ></div>
)
}
}
export default EchartsTest
// 父组件调用该组件
import EchartsTest from 'components/Echarts/lineCharts'; // 引入上述组件
const option = { echarts 配置项 } // 将后台数据放入echarts配置项中组织好echarts配置项 此处省略可查看echarts官网option各类配置项
<EchartsTest option={option} width={'90%'} />