Created
August 2, 2021 06:34
-
-
Save ExcitedSpider/6fa3a84ab55286684ef241f4873f5faf to your computer and use it in GitHub Desktop.
simple hooks to use echarts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface UseEchartsOptions { | |
/** | |
* render root | |
*/ | |
renderRootRef: React.RefObject<HTMLDivElement | HTMLCanvasElement>; | |
/** | |
* `setOption` 1st param object | |
*/ | |
echartsOption: EChartOption; | |
/** | |
* `setOption` 2nd param object | |
*/ | |
echartsSetOptionOpt?: any; | |
on?: { | |
[eventName: string]: (...params: any[]) => void; | |
}; | |
/** | |
* 调试模式 | |
*/ | |
debug?: boolean; | |
} | |
export const useEcharts = (options: UseEchartsOptions) => { | |
const { renderRootRef, echartsOption, echartsSetOptionOpt, debug, on: onEventMap } = options; | |
const chartInsRef = useRef<ECharts>(); | |
/** | |
* 初始化 echarts | |
* 在组件生命周期内只会执行一次,清理一次 | |
*/ | |
useEffect(() => { | |
if (renderRootRef.current) { | |
// 如果已经有一个 echarts instance,先 dispose 掉 | |
if (getInstanceByDom(renderRootRef.current)) { | |
console.warn('Element already has a chart instance! Check if there is memory leak.'); | |
getInstanceByDom(renderRootRef.current).dispose(); | |
} | |
chartInsRef.current = init(renderRootRef.current); | |
if (onEventMap) { | |
Object.keys(onEventMap).forEach((name) => { | |
chartInsRef.current?.on(name, onEventMap[name]); | |
}); | |
} | |
} | |
return () => { | |
chartInsRef.current?.dispose(); | |
}; | |
}, []); | |
const oldOption = useRef<any>(); | |
// resiponsive option | |
useEffect(() => { | |
// use lodash deep camparison | |
if (echartsOption && (!oldOption.current || !isEqual(oldOption.current, echartsOption))) { | |
if (debug) { | |
console.log('set chart option', echartsOption); | |
} | |
chartInsRef.current?.setOption(echartsOption, echartsSetOptionOpt); | |
oldOption.current = echartsOption; | |
} | |
}, [echartsOption]); | |
return { chartInsRef }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment