chart.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * ECharts 组件基础部分
  3. * 传入 option 和渲染方式 renderer
  4. * */
  5. import React, { PureComponent } from "react";
  6. import * as echarts from "echarts";
  7. import "zrender/lib/svg/svg";
  8. import { debounce } from "./index"; // 一个节流函数
  9. export default class Chart extends PureComponent {
  10. constructor(props) {
  11. super(props);
  12. this.state = {
  13. width: "100%",
  14. height: "100%",
  15. };
  16. this.chart = null;
  17. }
  18. async componentDidMount() {
  19. // 初始化图表
  20. await this.initChart(this.el);
  21. // 将传入的配置(包含数据)注入
  22. this.setOption(this.props.option);
  23. // 监听屏幕缩放,重新绘制 echart 图表
  24. window.addEventListener("resize", debounce(this.resize, 100));
  25. }
  26. componentDidUpdate() {
  27. // 每次更新组件都重置
  28. this.setOption(this.props.option);
  29. }
  30. componentWillUnmount() {
  31. // 组件卸载前卸载图表
  32. this.dispose();
  33. }
  34. render() {
  35. const { width, height } = this.state;
  36. return (
  37. <div
  38. className="default-chart"
  39. ref={(el) => (this.el = el)}
  40. style={{ width, height }}
  41. />
  42. );
  43. }
  44. initChart = (el) => {
  45. // renderer 用于配置渲染方式 可以是 svg 或者 canvas
  46. const renderer = this.props.renderer || "canvas";
  47. return new Promise((resolve) => {
  48. setTimeout(() => {
  49. this.chart = echarts.init(el, null, {
  50. renderer,
  51. width: "auto",
  52. height: "auto",
  53. });
  54. resolve();
  55. }, 0);
  56. });
  57. };
  58. setOption = (option) => {
  59. if (!this.chart) {
  60. return;
  61. }
  62. const { notMerge, lazyUpdate, onClick } = this.props;
  63. this.chart.setOption(option, notMerge, lazyUpdate);
  64. if (onClick) {
  65. this.chart.on("click", onClick);
  66. }
  67. };
  68. dispose = () => {
  69. if (!this.chart) {
  70. return;
  71. }
  72. this.chart.dispose();
  73. this.chart = null;
  74. };
  75. resize = () => {
  76. this.chart && this.chart.resize();
  77. };
  78. getInstance = () => {
  79. return this.chart;
  80. };
  81. }