当前位置:首页 > React

react中如何引入echarts

2026-01-24 17:27:46React

安装 ECharts 依赖

在项目中安装 ECharts 核心库和 React 适配器:

npm install echarts echarts-for-react

基础引入方式

通过 echarts-for-react 组件直接渲染图表:

import React from 'react';
import ReactECharts from 'echarts-for-react';

function ChartComponent() {
  const option = {
    xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
    yAxis: { type: 'value' },
    series: [{ data: [820, 932, 901], type: 'line' }]
  };

  return <ReactECharts option={option} style={{ height: 400 }} />;
}

按需引入模块

为减小打包体积,可仅引入需要的 ECharts 模块:

import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([LineChart, GridComponent, CanvasRenderer]);

// 后续使用方式与基础引入相同

动态主题切换

支持运行时切换主题:

import { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';

function ThemedChart() {
  const [theme, setTheme] = useState('light');
  const option = { /* 图表配置 */ };

  useEffect(() => {
    // 注册主题
    echarts.registerTheme('dark', { backgroundColor: '#333' });
  }, []);

  return (
    <>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        切换主题
      </button>
      <ReactECharts 
        option={option} 
        theme={theme}
        style={{ height: 400 }}
      />
    </>
  );
}

事件绑定

通过 onEvents 属性绑定图表事件:

<ReactECharts
  option={option}
  onEvents={{
    click: (params) => console.log('图表点击事件', params),
    legendselectchanged: (params) => console.log('图例切换', params)
  }}
/>

手动初始化

需要直接操作 ECharts 实例时:

import React, { useRef } from 'react';
import * as echarts from 'echarts';

function ManualChart() {
  const chartRef = useRef(null);

  useEffect(() => {
    const chart = echarts.init(chartRef.current);
    chart.setOption({ /* 配置项 */ });
    return () => chart.dispose();
  }, []);

  return <div ref={chartRef} style={{ width: '100%', height: 400 }} />;
}

react中如何引入echarts

标签: reactecharts
分享给朋友:

相关文章

react 如何执行

react 如何执行

安装 Node.js 和 npm React 开发需要 Node.js 环境,因为它提供了 npm(或 yarn)包管理工具。从 Node.js 官网 下载并安装最新 LTS 版本。安装完成后,在终端…

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment…

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何遍历

react如何遍历

遍历数组或对象的方法 在React中,遍历数组或对象通常用于渲染列表或动态生成内容。以下是几种常见的遍历方法: 使用map遍历数组map是遍历数组并返回新数组的高阶函数,适合渲染列表。…