基於React Hooks 封裝一個echart元件
阿新 • • 發佈:2022-03-13
基於React Hooks 封裝一個Echarts元件
官網 https://echarts.apache.org/zh/index.html
1 Echarts全域性配置
echarts.config.js
// 引入 echarts 核心模組,核心模組提供了 echarts 使用必須要的介面。 import * as echarts from 'echarts/core'; // 引入柱狀圖圖表,圖表字尾都為 Chart import { BarChart,PieChart } from 'echarts/charts'; // 引入提示框,標題,直角座標系,資料集,內建資料轉換器元件,元件字尾都為 Component import { TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, LegendComponent } from 'echarts/components'; // 標籤自動佈局,全域性過渡動畫等特性 import { LabelLayout, UniversalTransition } from 'echarts/features'; // 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必須的一步 import { CanvasRenderer } from 'echarts/renderers'; // 註冊必須的元件 echarts.use([ TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, BarChart, LabelLayout, UniversalTransition, CanvasRenderer, LegendComponent, PieChart ]); export default echarts;
2 封裝React Echarts元件
import React, { useEffect, useRef } from 'react' import echarts from './echarts.config' import './ReactEchartComponent.css' export const ReactEchartComponent = (props) => { const { option: chartOptions, clickHandler, className } = props const dom = useRef() useEffect(() => { if (chartOptions) { const chart = echarts.init(dom.current) // chart.showLoading() clickHandler && chart.on('click', clickHandler) chart.setOption(chartOptions) // chart.hideLoading() } }, [chartOptions, clickHandler]) return ( <div className={className} ref={dom}></div> ) }
3 使用元件
import React from 'react' import { useCallback } from 'react'; import { ReactEchartComponent } from '../component/ReactEchartComponent'; import './ReactEchartDemo.css' const option = { legend: { orient: 'vertical', x: 'right', data: ['A', 'B', 'C', 'D', 'E'] }, series: [ { type: 'pie', radius: ['50%', '70%'], avoidLabelOverlap: false, label: { show: false, position: 'left', emphasis: { show: true } }, labelLine: { show: true }, emphasis: { label: { show: true, fontSize: '30', fontWeight: 'bold' } }, data: [ { value: 335, name: 'A' }, { value: 310, name: 'B' }, { value: 234, name: 'C' }, { value: 135, name: 'D' }, { value: 1548, name: 'E' } ] } ] }; export const ReactEchartDemo = () => { const clickHandler = useCallback( (e) => { console.log(e); }, []) return ( <div className='con'> <ReactEchartComponent clickHandler={clickHandler} className="chart" option={option}></ReactEchartComponent> </div> ) }