diff --git a/package.json b/package.json index b25ad4de88168692f92f1bf84f3934b85519e3d9..2cd1ca87acaa045256b31fc4a1f2b9b7df4cef78 100644 --- a/package.json +++ b/package.json @@ -57,4 +57,4 @@ "unplugin-auto-import": "^0.15.0", "vite": "^4.1.0" } -} \ No newline at end of file +} diff --git a/src/hooks/useEcharts.ts b/src/hooks/useEcharts.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0e4e6209651dbca4cb9d3945f04d376a14217ff --- /dev/null +++ b/src/hooks/useEcharts.ts @@ -0,0 +1,51 @@ +import { useCallback, useEffect, useRef } from 'react' +import * as echarts from 'echarts' + +/** + * 使用Echarts + * @param options - 绘制echarts的参数 + * @param data - 数据 + */ +export const useEcharts = (options: echarts.EChartsCoreOption, data?: unknown) => { + const echartsRef = useRef() + const htmlDivRef = useRef(null) + + const dispose = () => { + if (htmlDivRef.current) { + echartsRef.current?.dispose() + } + } + + const init = useCallback(() => { + if (options) { + dispose() + if (htmlDivRef.current) { + echartsRef.current = echarts.init(htmlDivRef.current) + echartsRef.current.setOption(options) + echartsRef.current?.resize() + } + } + }, [options]) + + useEffect(() => { + if (options) init() + }, [init, options]) + + useEffect(() => { + init() + window.addEventListener('resize', init, false) + + return () => { + window.removeEventListener('resize', init) + dispose() + } + }, []) + + useEffect(() => { + if (data) { + echartsRef?.current?.setOption(options) + } + }, [data]) + + return [htmlDivRef, init] as const +} diff --git a/src/pages/charts/basic/index.tsx b/src/pages/charts/basic/index.tsx index ae3610109e3f4892a895184fd50b7d109650276a..c41f261d9ed1671463437eadb2f6ef30d9ac1c81 100644 --- a/src/pages/charts/basic/index.tsx +++ b/src/pages/charts/basic/index.tsx @@ -1,9 +1,10 @@ import { FC } from 'react' import { Card } from 'antd' import View from '@/components/View' -import ReactEcharts from 'echarts-for-react' +import { useEcharts } from '@/hooks/useEcharts' +import type { EChartsOption } from 'echarts' -const option = { +const option: EChartsOption = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], @@ -20,13 +21,8 @@ const option = { } const Basic: FC = () => { - return ( - - - - - - ) + const [echartsRef] = useEcharts(option) + return
} export default Basic diff --git a/src/styles/common.scss b/src/styles/common.scss index cee952346b42e6dc8281cd88ad685da9476f6419..b3470a99cf3ecdff95ebca19c3dd0da763f82b85 100644 --- a/src/styles/common.scss +++ b/src/styles/common.scss @@ -68,3 +68,10 @@ input{ [hidden]{ display:none !important; } + +.content-box { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; +} \ No newline at end of file