PieChartModule.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. data: [
  3. { value: 1048, name: 'Search Engine' },
  4. { value: 735, name: 'Direct' },
  5. { value: 580, name: 'Email' },
  6. { value: 484, name: 'Union Ads' },
  7. { value: 300, name: 'Video Ads' },
  8. ],
  9. */
  10. import { Empty } from 'antd';
  11. import * as echarts from 'echarts';
  12. import { useEffect, useRef } from 'react';
  13. import styles from './index.less';
  14. //图表模块
  15. const PieChartModule = (props) => {
  16. const chartDomRef = useRef();
  17. const chartRef = useRef();
  18. const { data } = props;
  19. useEffect(() => {
  20. chartRef.current = echarts.init(chartDomRef.current);
  21. window.addEventListener('resize', resetChart);
  22. return () => window.removeEventListener('resize', resetChart);
  23. }, []);
  24. useEffect(() => {
  25. if (!chartRef.current || !data) return;
  26. const option = { ...defaultOption };
  27. option.series[0].data = data;
  28. chartRef.current.clear();
  29. chartRef.current.setOption(option);
  30. chartRef.current.resize();
  31. }, [data]);
  32. const resetChart = () => {
  33. if (chartRef.current) chartRef.current.resize();
  34. };
  35. const getStyle = () => {
  36. if (data && data.length != 0) return { width: '100%', height: '100%' };
  37. else return { width: '100%', height: '100%', display: 'none' };
  38. };
  39. return (
  40. <div className={styles.content}>
  41. <div style={getStyle()} ref={chartDomRef} />
  42. {(!data || data.length == 0) && <Empty />}
  43. </div>
  44. );
  45. };
  46. export default PieChartModule;
  47. const colors = [
  48. '#5470c6',
  49. '#91cc75',
  50. '#fac858',
  51. '#ee6666',
  52. '#73c0de',
  53. '#3ba272',
  54. '#fc8452',
  55. '#9a60b4',
  56. '#ea7ccc',
  57. ];
  58. const defaultOption = {
  59. color: colors,
  60. tooltip: {
  61. trigger: 'item',
  62. formatter: '{b} : {d}% ({c})',
  63. },
  64. series: [
  65. {
  66. type: 'pie',
  67. radius: '70%',
  68. data: [
  69. { value: 1048, name: 'Search Engine' },
  70. { value: 735, name: 'Direct' },
  71. { value: 580, name: 'Email' },
  72. { value: 484, name: 'Union Ads' },
  73. { value: 300, name: 'Video Ads' },
  74. ],
  75. label: {
  76. fontSize: '0.18rem',
  77. },
  78. emphasis: {
  79. itemStyle: {
  80. shadowBlur: 10,
  81. shadowOffsetX: 0,
  82. shadowColor: 'rgba(0, 0, 0, 0.5)',
  83. },
  84. label: {
  85. fontSize: '0.24rem',
  86. },
  87. },
  88. },
  89. ],
  90. };