当前位置:首页 > React

react中如何引入echarts

2026-01-24 17:27:46React

安装 ECharts 依赖

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

npm install echarts echarts-for-react

基础引入方式

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

react中如何引入echarts

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]);

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

动态主题切换

支持运行时切换主题:

react中如何引入echarts

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 }} />;
}

标签: reactecharts
分享给朋友:

相关文章

如何创建react

如何创建react

创建React项目的步骤 使用Create React App工具快速搭建React项目。确保已安装Node.js(版本需≥14.0.0)和npm(版本需≥5.6)。 打开终端或命令行工具,运行以下…

react如何遍历

react如何遍历

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

如何运行react

如何运行react

运行 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网 Node.js 下载并安装最新稳定版本。安装完成后,验证版本: node…

react如何重启

react如何重启

重启 React 应用的方法 重新加载当前页面 使用 window.location.reload() 强制刷新页面,这会重新加载整个应用并重置所有状态。 window.location…

react如何建项目

react如何建项目

创建React项目的几种方法 使用官方工具Create React App(CRA) npx create-react-app my-app 这条命令会创建一个名为my-app的新React项目,包含…

小白如何搭建react

小白如何搭建react

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网下载安装包(https://nodejs.org/),选择 LTS 版本。安装完成后,终端运行以下命令验证版…