Skip to content

Instantly share code, notes, and snippets.

@suhaotian
Created November 17, 2021 08:57
Show Gist options
  • Save suhaotian/d1e2961041cd4163f5cb561efe62ab74 to your computer and use it in GitHub Desktop.
Save suhaotian/d1e2961041cd4163f5cb561efe62ab74 to your computer and use it in GitHub Desktop.
echarts with typescript
import React, { useState, useRef, useEffect, useMemo, useLayoutEffect, useImperativeHandle, forwardRef, Ref } from 'react'
import echarts, { ECOption } from './echarts-ref';
export type EchartProp = {
option: ECOption,
style?: {
width: string,
height: string
}
className?: string
}
const removeUndefined = (obj: object) => {
for (let key in obj) {
if (obj[key as keyof typeof obj] === undefined) {
delete obj[key as keyof typeof obj]
}
}
return obj
}
const Echart = ({ option, className, style = { width: '100%', height: '100%' } }: EchartProp, ref: Ref<echarts.ECharts | undefined
>) => {
const chartRef = useRef<HTMLDivElement>(null)
const [echartsInstance, setEchartsInstance] = useState<echarts.ECharts>()
useLayoutEffect(() => {
const instance = echarts.init(chartRef.current as HTMLDivElement);
setEchartsInstance(instance)
return () => {
instance.dispose();
}
}, [])
useEffect(() => {
const handleResize = () => {
echartsInstance?.resize()
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [echartsInstance])
useEffect(() => {
echartsInstance?.setOption(option)
}, [echartsInstance, option])
useImperativeHandle(ref, () => (echartsInstance));
const obj = useMemo(() => {
return removeUndefined({ option, className, style });
}, [option, className, style])
return (
<div ref={chartRef} {...obj} />
)
}
export default forwardRef(Echart);
import * as echarts from "echarts/core";
import {
BarChart,
// 系列类型的定义后缀都为 SeriesOption
BarSeriesOption,
LineChart,
LineSeriesOption,
} from "echarts/charts";
import {
TitleComponent,
// 组件类型的定义后缀都为 ComponentOption
TitleComponentOption,
GridComponent,
GridComponentOption,
// 数据集组件
DatasetComponent,
DatasetComponentOption,
// 内置数据转换器组件 (filter, sort)
TransformComponent,
TooltipComponent,
} from "echarts/components";
import { LabelLayout, UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
export type ECOption = echarts.ComposeOption<
| BarSeriesOption
| LineSeriesOption
| TitleComponentOption
| GridComponentOption
| DatasetComponentOption
>;
// 注册必须的组件
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
BarChart,
LineChart,
LabelLayout,
UniversalTransition,
CanvasRenderer,
]);
export default echarts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment