| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- import { useEffect, useRef } from 'react';
- import * as echarts from 'echarts/core';
- import type { ECharts, EChartsOption } from 'echarts';
- import {
- GridComponent,
- LegendComponent,
- MarkLineComponent,
- TitleComponent,
- ToolboxComponent,
- TooltipComponent,
- } from 'echarts/components';
- import { BarChart, LineChart, PieChart } from 'echarts/charts';
- import { UniversalTransition } from 'echarts/features';
- import { CanvasRenderer } from 'echarts/renderers';
- import Style from './index.less';
- import classNames from 'classnames';
- export interface EchartsProps {
- options?: EChartsOption;
- className?: string;
- }
- echarts.use([
- TitleComponent,
- ToolboxComponent,
- TooltipComponent,
- GridComponent,
- LegendComponent,
- LineChart,
- CanvasRenderer,
- UniversalTransition,
- BarChart,
- MarkLineComponent,
- PieChart,
- ]);
- const DefaultOptions = {
- xAxis: {
- type: 'category',
- data: [0],
- },
- yAxis: {
- type: 'value',
- },
- series: [
- {
- data: [],
- type: 'line',
- },
- ],
- };
- export { echarts };
- export default (props: EchartsProps) => {
- const chartsRef = useRef<any>(null);
- const initEcharts = (dom: HTMLDivElement) => {
- if (!chartsRef.current) {
- chartsRef.current = echarts.init(dom);
- if (props.options) {
- chartsRef.current.setOption(props.options);
- } else {
- chartsRef.current.setOption(DefaultOptions);
- }
- }
- };
- const updateSize = () => {
- if (chartsRef.current) {
- // 自适应屏幕变化
- (chartsRef.current as ECharts).resize();
- }
- };
- useEffect(() => {
- setTimeout(() => (window as Window).addEventListener('resize', updateSize), 100);
- return () => {
- (window as Window).removeEventListener('resize', updateSize);
- };
- }, []);
- useEffect(() => {
- if (chartsRef.current && props.options) {
- chartsRef.current.setOption(props.options);
- }
- }, [props.options]);
- return (
- <div
- className={classNames(Style['content'], props.className)}
- ref={(ref) => {
- if (ref) {
- setTimeout(() => {
- initEcharts(ref);
- }, 100);
- }
- }}
- />
- );
- };
|