Encapsulate Echarts graphics into class components in React

Preface: There is a special visualization tool AntV in React, but relying on this visualization alone is sometimes far from completing the project development requirements, so consider introducing the most common Echarts visualization tool, and introducing it in React requires its It is encapsulated in the form of components and used. This section briefly introduces how to encapsulate Echarts. The official website of the tool is as follows: Apache ECharts

1. First create an empty component in React

class Gauge2 extends Component{  

}
export default Gauge2;

Prepare to store the graphic attributes and data required in Echarts.

2. Select the appropriate graphics in Echarts and introduce dependencies as needed. (Take a basic line chart as an example)

import React, { Component } from "react";
import * as echarts from "echarts";
import "echarts-gl";  //该依赖可不要
//以上依赖的前提是你需要下载 Echarts 的
class Gauge2 extends Component{  

}
export default Gauge2;

3. Introduce data and complete the code in the component

import React, { Component } from "react";
import * as echarts from "echarts";
import "echarts-gl";  //该依赖可不要
//以上依赖的前提是你需要下载 Echarts 在 React 中
class Gauge2 extends Component{  
     componentDidMount() {   //初始化组件,只执行一次
        this.initEcharts();
      }
     componentDidUpdate(){   // 组件更新时也会调用。
        this.initEcharts();
     }
      initEcharts() {     
        const myChart = echarts.init(   
          document.getElementById("main") as HTMLElement
        );
        myChart.setOption({  //下列数据可以直接按照可视化图里面的东西进行替换
            xAxis: {
                type: 'category',
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
              },
              yAxis: {
                type: 'value'
              },
              series: [
                {
                  data: [150, 230, 224, 218, 135, 147, 260],
                  type: 'line'
                }
              ]
        });
    }
    render(): React.ReactNode{   //挂载
        return <div id="main" style={
   
   {width:'100px',height:'100px'}}></div>
    }
}
export default Gauge2;

Rendering:  

 Finally: If you need to introduce other graphics, you can directly replace the data in myChart.setOption({}). Just copy and paste the content in the picture below:

Guess you like

Origin blog.csdn.net/youyudehan/article/details/128257117