Media Query 实现(移动端自适应 - echarts

性能高、效果好,适用多个图表。

echarts 的 resize 实现

改变图表尺寸,在容器大小发生改变时需要手动调用。性能低,只适用单个图表。

实现

  1. import React from 'react';
  2. import { useSize, useUpdateEffect } from 'ahooks';
  3. interface ResponsChartsProps {
  4. myChart: React.MutableRefObject<any>;
  5. chartRef: React.MutableRefObject<any>;
  6. }
  7. const ResponsCharts: React.FC<ResponsChartsProps> = ({ myChart, chartRef }) => {
  8. const size = useSize(chartRef);
  9. useUpdateEffect(() => {
  10. myChart?.current?.resize();
  11. }, [size]);
  12. return null;
  13. };
  14. export default ResponsCharts;

使用

  1. import { useRef, useEffect } from 'react';
  2. import * as echarts from 'echarts';
  3. import ResponsCharts from './ResponsCharts';
  4. import styles from './index.less';
  5. const option: echarts.EChartsOption = {
  6. ...
  7. };
  8. export default () => {
  9. const chartRef = useRef<HTMLDivElement>(null);
  10. const myChart = useRef<echarts.ECharts>();
  11. const initChart = () => {
  12. if (!myChart.current && chartRef?.current) {
  13. myChart.current = echarts.init(chartRef.current);
  14. myChart.current.setOption(option);
  15. }
  16. };
  17. useEffect(() => {
  18. initChart();
  19. }, []);
  20. return (
  21. <div style={{ width: '100%', height: '100%' }}>
  22. <div style={{ width: '100%', height: '100%' }} ref={chartRef} />
  23. <ResponsCharts myChart={myChart} chartRef={chartRef} />
  24. </div>
  25. );
  26. };