美文网首页
React通用图表组件,使用Echarts封装

React通用图表组件,使用Echarts封装

作者: 剑指流云 | 来源:发表于2023-07-24 16:11 被阅读0次

组件内容

  • 使用了uuid,目的是避免id字段需要频繁从外部传入,然而id除了标明容器的位置,并没有啥卵用,所以使用uuid随机生成
yarn add uuid
yarn add echarts
  • 组件没有对图表单击事件注册,需要可以自己加代码
import React from 'react';

// 第二步引入 echarts
import * as echarts from 'echarts';
import * as uuid from 'uuid';
class Reports extends React.Component {
  readonly state: Readonly<{ charts: any }> = {
    charts: null,
  };
  readonly uuid = uuid.v4();
  componentDidMount() {
    // 触发initCharts
    this.initCharts();
  }

  props!: Readonly<{ option: any; height?: number }> & Readonly<{ children?: React.ReactNode }>;
  // 第三步初始化
  initCharts = () => {
    const option = this.props.option || {};
    const myChart = echarts.init(document.getElementById(this.uuid));
    myChart.setOption(option);
    window.addEventListener('resize', function () {
      myChart.resize();
    });
    this.setState({
      charts: myChart,
    });
  };

  shouldComponentUpdate(nextProps: Readonly<{ option: any }>): boolean {
    if (this.state.charts) {
      this.state.charts.setOption(nextProps.option || {});
    }
    return true;
  }

  render() {
    return <div id={this.uuid} className="full-size " style={{ minHeight: this.props.height|| 200 }} />;
  }
}

export default Reports;

组件全局类

  • full-size 目的是为了使组件继承父容器宽高,实现自适应
.full-size{
  width:"100%;
  height:"100%";
}

相关文章

网友评论

      本文标题:React通用图表组件,使用Echarts封装

      本文链接:https://www.haomeiwen.com/subject/enfcpdtx.html