1
1
import { throttle } from 'lodash' ;
2
- import { useCallback , useEffect , useRef } from 'react' ;
2
+ import {
3
+ forwardRef ,
4
+ useCallback ,
5
+ useEffect ,
6
+ useImperativeHandle ,
7
+ useRef
8
+ } from 'react' ;
3
9
import echarts , { ECOption } from '.' ;
4
10
5
11
const Chart : React . FC < {
6
12
options : ECOption ;
7
13
height : number | string ;
8
14
width : number | string ;
9
- } > = ( { options, width, height } ) => {
15
+ ref ?: any ;
16
+ } > = forwardRef ( ( { options, width, height } , ref ) => {
10
17
const container = useRef < HTMLDivElement > ( null ) ;
11
18
const chart = useRef < echarts . EChartsType > ( ) ;
12
19
const resizeable = useRef ( false ) ;
13
20
const resizeObserver = useRef < ResizeObserver > ( ) ;
14
21
22
+ useImperativeHandle ( ref , ( ) => {
23
+ return {
24
+ chart : chart . current
25
+ } ;
26
+ } ) ;
27
+
15
28
const init = useCallback ( ( ) => {
16
29
if ( container . current ) {
17
30
chart . current ?. clear ( ) ;
@@ -44,18 +57,9 @@ const Chart: React.FC<{
44
57
resizeable . current = false ;
45
58
resize ( ) ;
46
59
setOption ( options ) ;
60
+ resizeable . current = true ;
47
61
} , [ options ] ) ;
48
62
49
- useEffect ( ( ) => {
50
- let timer : any = null ;
51
- timer = setTimeout ( ( ) => {
52
- resizeable . current = true ;
53
- } , 300 ) ;
54
- return ( ) => {
55
- clearTimeout ( timer ) ;
56
- } ;
57
- } , [ ] ) ;
58
-
59
63
useEffect ( ( ) => {
60
64
const handleResize = throttle ( ( ) => {
61
65
if ( resizeable . current ) {
@@ -75,7 +79,22 @@ const Chart: React.FC<{
75
79
} ;
76
80
} , [ ] ) ;
77
81
78
- return < div ref = { container } style = { { width : width , height } } > </ div > ;
79
- } ;
82
+ // resize on window resize
83
+ // useEffect(() => {
84
+ // const handleResize = throttle(() => {
85
+ // chart.current?.resize();
86
+ // }, 100);
87
+ // window.addEventListener('resize', handleResize);
88
+ // return () => {
89
+ // window.removeEventListener('resize', handleResize);
90
+ // };
91
+ // }, []);
92
+
93
+ return (
94
+ < div className = "chart-wrapper" style = { { width : width , height } } >
95
+ < div ref = { container } style = { { width : width , height } } > </ div >
96
+ </ div >
97
+ ) ;
98
+ } ) ;
80
99
81
100
export default Chart ;
0 commit comments