封装代码如下
import React, { Component } from 'react';
import echarts from 'echarts';
class MyEcharts extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
this.initChart();
window.addEventListener('resize', this.resize, false);
}
initChart() {
this.myChart = echarts.init(this.myRef.current);
this.myChart.setOption(this.props.option);
}
resize = () => {
if (this.myChart) {
this.myChart.resize();
}
}
shouldComponentUpdate(nextProps) {
if (this.props.option !== nextProps.option) {
this.myChart.setOption(nextProps.option);
return false;
}
}
componentWillUnmount() {
this.myChart.dispose();
this.myChart = null;
window.removeEventListener('resize', this.resize, false);
}
render() {
let height = this.props.height || '100%';
let width = this.props.width || '100%';
return (
<div ref={this.myRef} style={{ width, height }}></div>
);
}
}
export default MyEcharts;
调用如下
import React, { Component } from 'react';
import MyEcharts from 'MyEcharts';
export default class Demo extends Component {
constructor(props) {
super(props);
this.state = {
lineOption: {...}
};
}
render() {
let { lineOption } = this.state;
return (
<MyEcharts option={lineOption} height="250px" />
);
}
}