当我使用功能性反应组件时,如何从 HighchartsReact 组件访问图表到 ResponsiveGridLayout 组件

How to get access to the chart from HighchartsReact component to ResponsiveGridLayout component when I'm using functional react component

我正在尝试使用 react 和 react-grid-layout 实现 highChart。图表应根据反应网格布局调整大小,为此,我需要在 onResizeStop 中传递 chart.reflow() ResponsiveGridLayout 的道具。我可以访问 HighchartsReact 的回调道具中的图表,但我无法弄清楚如何访问 ResponsiveGridLayout 组件中的图表以将其传递到 onResizeStop 道具中。

import { Responsive, WidthProvider } from 'react-grid-layout';
import Highcharts, { chart } from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import { useRef, useState } from "react"
import styles from './Blocks.module.css';

const ResponsiveGridLayout = WidthProvider(Responsive);

const options1 = {
    title: {
        text: 'My chart 1'
    },
    series: [{
        type:'bar',
        data: [1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7]
    }],

  }

const Blocks = (props) => {

    
    const layout1 = [
        { i: "1", x: 0, y: 0, w: 8, h: 8 },
    ]

   const handleResize = chart => {
    chart.reflow()
   }

    return (
        <div className={styles.blocks}>
            <ResponsiveGridLayout 
                className="layout" 
                layouts={layout1}   
                autoSize={true}
                allow-resize={true}
                isDraggable
                isRearrangeable
                isResizable
                onResizeStop={handleResize}
                breakpoints={{lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}}
                cols={{lg: 12, md: 10, sm: 6, xs: 4, xxs: 2}} 
             >

                <div className={styles.container} key="1" >
                    <HighchartsReact 
                        containerProps = {{ className: styles.chartContainer }}
                        highcharts = { Highcharts } 
                        options = { options1 }
                        callback = { chart => chart}
                    />
                </div>
            </ResponsiveGridLayout>
        </div>
    )
}

export default Blocks

您可以使用 React useRef 钩子获取图表实例:

  const chartComponent = useRef(null);

  const handleResize = () => {
    const chart = chartComponent.current?.chart;
    if (chart) {
      chart.reflow();
    }
  };

  return (
    <HighchartsReact
      ref={chartComponent}
      ...
    />
  );

现场演示: https://codesandbox.io/s/highcharts-react-demo-fork-n4y01?file=/demo.jsx

文档: https://github.com/highcharts/highcharts-react#how-to-get-a-chart-instance