Skip to content

小程序使用echarts

约 588 字大约 2 分钟

小程序taroecharts

2025-05-02

原文链接:https://blog.csdn.net/weixin_59306092/article/details/125786453

由于小程序对包的体积限制我们需要定制echarts

然后就是把这个项目下载自己的电脑上,但是这里有一个非常重要的一个点,决定你的图表是否能够出来,在我下面这张图中圈的位置,一定要注意自己下的是哪个版本,因为echarts.js很大,一般使用的话,都直接在官网定制,小程序中不会放很多echarts图表,否则整个项目太大了,会跑不起来的。

  • 到echarts官网下载图表

  • 点击下载,进入定制页面 :往最下面翻,方法三:在线定制

  • 更具需求下载对应计即可
  • 替换下载的gitee上下载的 ec-canvas 中的js文件
  • 自己在taro中封装的

    import { useRef, useEffect } from 'react';
    import { View } from '@tarojs/components';
    import Echarts from 'taro-react-echarts';
    // 导入 ECharts 库
    // 换为自己的
    import * as echarts from '../../ec-canvas/echarts.min.js'; // <-- 改为正确的名称 // <-- 改为正确的名称
    import Taro from '@tarojs/taro'; // **确保导入 Taro**
    
    export default function LineChartDemo({ option }) {
      // echartsRef 会引用 taro-react-echarts 组件的实例,
      // taro-react-echarts 的 ref 通常会暴露底层的 ECharts 实例
      const echartsRef = useRef(null);
    
    
    
      // 在组件挂载后调用 resize
      useEffect(() => {
    
    
        // 使用 Taro.nextTick 确保在 DOM 更新完成后执行
        Taro.nextTick(() => {
          // 检查 ref 是否存在以及是否是有效的 ECharts 实例
          if (echartsRef.current && typeof echartsRef.current.resize === 'function') {
            echartsRef.current.resize();
    
          } else {
            console.warn('Echarts ref is not available or resize method is missing.');
          }
        });
    
        // 返回一个清理函数,在组件卸载时销毁 ECharts 实例
        // taro-react-echarts 内部通常会处理销毁,但为了健壮性可以保留
        return () => {
          if (echartsRef.current && typeof echartsRef.current.dispose === 'function') {
            echartsRef.current.dispose();
          }
        };
    
      }, []); // 空依赖数组表示只在组件挂载和卸载时执行
    
      return (
        // 确保 View 有明确的尺寸
        <View style={{ width: '100%', height: '100%' }}>
          <Echarts
            echarts={echarts}
            option={option}
            ref={echartsRef} // 将 ref 传递给 Echarts 组件
            isPage={false} // **明确设置为 false,因为是组件内的图表**
            style={{ width: '100%', height: '100%' }}
          />
        </View>
      );
    }