您的当前位置:首页正文

Echarts在react项目中的使用

来源:华拓网

一、Echarts简介

二、如何使用

1、进入官网后,点击
官网
2、任选一个实例点击进入,即可进入左侧代码,右侧图标的页面,我们可以在左侧编辑代码,右侧将实时显示我们做出的改变。笔者进入的是
实例
3、之后我们将在左侧代码中看到诸多配置项,例如title,tooltip,legend等。
image.png
4、我们应该到那里去了解这些配置项的含义呢?这时候我们可以再次打开一个官网首页,点击文档下的
配置项手册
配置项
5、了解了基本配置项后,回到我们点开的实例进行操作,我们更改title下的text之后,图标标题也会随之改变。需要改哪个部分,只要如此一般查看配置项手册即可。
修改标题

三、如何应用到React项目中

0、装包
npm install echarts --save
1、Echarts图表在应用时一般都是作为独立文件被引用到所需页面,笔者首先提供一个模板代码,使用时,只需要把我们在官方实例中修改好的代码(option里边的内容)放到模板代码的return()中即可(详见截图)
此部分放入return
import React, { Component } from 'react';
import echarts from 'echarts';

export class Echart extends  {
  constructor(props) {
    super(props);
    this.setPieOption = this.setPieOption.bind(this);
    this.initPie = this.initPie.bind(this);
  }

  initPie() {
    const { data } = this.props; //外部传入的data数据
    let myChart = echarts.init(this.refs.PieEcharts); //初始化echarts
    //我们要定义一个setPieOption函数将data传入option里面
    let options = this.setPieOption(data);
    //设置options
    myChart.setOption(options);
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }

  componentDidMount() {
    this.initPie();
  }

  componentDidUpdate() {
    this.initPie();
  }

  render() {
    return (
      <div className="pie-react">
        <div ref="PieEcharts" style={{ width: this.props.width, height: this.props.height }}></div>
      </div>
    );
  }

  setPieOption(data) {
    return {
        //这里放官方实力中option中的内容
    }

  }
}

2、引用Echarts的文件
import { Echart } from './Echart'
import React, { Component } from 'react'
import { Echart } from './Echart'

export class EchartsUse extends Component {
  constructor(props) {
    super(props)
    this.state = {
    };
  };
  render() {
    return (
      <div style={{
        width: '100%',
        height: window.innerHeight,
        background: '#001D37',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
        <div style={{
          width: '500px',
          height: '300px',
          background: '#fff',
          padding: '30px',
          borderRadius: '10px'
        }}>

          <Echart
            height={'300px'}
          />
        </div>
      </div>
    )
  }
}

export default EchartsUse

四、最终效果

最终效果

欲知完整代码如何请见GitHub

git clone 

执行即可获取到完整项目文件