echarts.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import { useEffect, useRef } from 'react';
  2. import * as echarts from 'echarts/core';
  3. import type { ECharts, EChartsOption } from 'echarts';
  4. import {
  5. GridComponent,
  6. LegendComponent,
  7. MarkLineComponent,
  8. TitleComponent,
  9. ToolboxComponent,
  10. TooltipComponent,
  11. } from 'echarts/components';
  12. import { BarChart, LineChart, PieChart } from 'echarts/charts';
  13. import { UniversalTransition } from 'echarts/features';
  14. import { CanvasRenderer } from 'echarts/renderers';
  15. import Style from './index.less';
  16. import classNames from 'classnames';
  17. export interface EchartsProps {
  18. options?: EChartsOption;
  19. className?: string;
  20. }
  21. echarts.use([
  22. TitleComponent,
  23. ToolboxComponent,
  24. TooltipComponent,
  25. GridComponent,
  26. LegendComponent,
  27. LineChart,
  28. CanvasRenderer,
  29. UniversalTransition,
  30. BarChart,
  31. MarkLineComponent,
  32. PieChart,
  33. ]);
  34. const DefaultOptions = {
  35. xAxis: {
  36. type: 'category',
  37. data: [0],
  38. },
  39. yAxis: {
  40. type: 'value',
  41. },
  42. series: [
  43. {
  44. data: [],
  45. type: 'line',
  46. },
  47. ],
  48. };
  49. export { echarts };
  50. export default (props: EchartsProps) => {
  51. const chartsRef = useRef<any>(null);
  52. const initEcharts = (dom: HTMLDivElement) => {
  53. if (!chartsRef.current) {
  54. chartsRef.current = echarts.init(dom);
  55. if (props.options) {
  56. chartsRef.current.setOption(props.options);
  57. } else {
  58. chartsRef.current.setOption(DefaultOptions);
  59. }
  60. }
  61. };
  62. const updateSize = () => {
  63. if (chartsRef.current) {
  64. // 自适应屏幕变化
  65. (chartsRef.current as ECharts).resize();
  66. }
  67. };
  68. useEffect(() => {
  69. setTimeout(() => (window as Window).addEventListener('resize', updateSize), 100);
  70. return () => {
  71. (window as Window).removeEventListener('resize', updateSize);
  72. };
  73. }, []);
  74. useEffect(() => {
  75. if (chartsRef.current && props.options) {
  76. chartsRef.current.setOption(props.options);
  77. }
  78. }, [props.options]);
  79. return (
  80. <div
  81. className={classNames(Style['content'], props.className)}
  82. ref={(ref) => {
  83. if (ref) {
  84. setTimeout(() => {
  85. initEcharts(ref);
  86. }, 100);
  87. }
  88. }}
  89. />
  90. );
  91. };