Echarts 一个基于 JavaScript 的开源可视化图表库
1、如果要在你的项目中使用 Echarts , 实现先安装对应的包,从 npm 获取
npm install echarts
2、安装完成之后再文件内引入
import * as echarts from "echarts";
3、声明一个 ref 给展示图标的元素,声明属性值
const chartRef = useRef<any>(null);
注意:展示图标的元素一定要加宽高,否则看不到图表的
<><div ref={chartRef} style={{ width: "500px", height: "350px" }}></div></>
属性值
const optionData = {title: {text: "ECharts 入门示例",},tooltip: {},xAxis: {data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],},yAxis: {},series: [{name: "销量",type: "bar",data: [5, 20, 36, 10, 10, 20],},],};
4、使用,在挂载阶段渲染,关闭页面后销毁,以免内存泄漏
useEffect(() => {// 挂载阶段const chart = echarts.init(chartRef.current);chart.setOption(optionData);// 销毁return () => {chart.dispose();};}, []);
结果展示:
完整代码:
import * as echarts from "echarts";
import { useEffect, useRef } from "react";
const EchartsPage = () => {const chartRef = useRef<any>(null);const optionData = {title: {text: "ECharts 入门示例",},tooltip: {},xAxis: {data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],},yAxis: {},series: [{name: "销量",type: "bar",data: [5, 20, 36, 10, 10, 20],},],};useEffect(() => {// 挂载阶段const chart = echarts.init(chartRef.current);chart.setOption(optionData);// 销毁return () => {chart.dispose();};}, []);return (<><div ref={chartRef} style={{ width: "500px", height: "350px" }}></div></>);
};export default EchartsPage;