11import React , { useEffect , useRef , forwardRef } from 'react' ;
22
3- export type ReactG2PlotProps = {
3+ export type ReactG2PlotProps < O > = {
44 readonly className ?: string ;
55 readonly Ctor : any ;
6- readonly config : object ;
6+ readonly options : O ;
77} ;
88
99/**
10- * 一个基本可用的 G2Plot React 组件
10+ * 一个业务可用的 G2Plot React 组件
1111 */
12- export default forwardRef ( ( props : ReactG2PlotProps , ref : any ) => {
13- const { className, Ctor, config } = props ;
12+ export default forwardRef ( function < O = any > ( props : ReactG2PlotProps < O > , ref : any ) {
13+ const { className, Ctor, options } = props ;
1414
1515 const $dom = useRef ( undefined ) ;
1616 const plotRef = useRef ( undefined ) ;
@@ -29,31 +29,39 @@ export default forwardRef((props: ReactG2PlotProps, ref: any) => {
2929 }
3030
3131 /**
32- * 创建
32+ * 如果存在则更新,否则就创建
3333 */
34- function newPlot ( ) {
34+ function renderPlot ( ) {
3535 if ( plotRef . current ) {
36- plotRef . current . destroy ( ) ;
37- plotRef . current = undefined ;
36+ // update
37+ plotRef . current . update ( options ) ;
38+ } else {
39+ // new
40+ plotRef . current = new Ctor ( $dom . current , options ) ;
41+ plotRef . current . render ( ) ;
3842 }
3943
40- plotRef . current = new Ctor ( $dom . current , config ) ;
41-
4244 syncRef ( plotRef , ref ) ;
45+ }
4346
44- plotRef . current . render ( ) ;
47+ /**
48+ * 销毁
49+ */
50+ function destoryPlot ( ) {
51+ if ( plotRef . current ) {
52+ plotRef . current . destroy ( ) ;
53+ plotRef . current = undefined ;
54+ }
4555 }
4656
4757 useEffect ( ( ) => {
48- newPlot ( ) ;
58+ renderPlot ( ) ;
4959
5060 return ( ) => {
51- if ( plotRef . current ) {
52- plotRef . current . destroy ( ) ;
53- plotRef . current = undefined ;
54- }
61+ destoryPlot ( ) ;
5562 } ;
56- } , [ Ctor , config ] ) ;
63+ } , [ options , Ctor ] ) ;
5764
58- return < div className = { className } ref = { $dom } /> ;
65+ // 默认添加 g2plot-for-react 的 class
66+ return < div className = { `g2plot-for-react ${ className || '' } ` } ref = { $dom } /> ;
5967} ) ;
0 commit comments