You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数式组件中如何将HighchartsReact实例传给ResponsiveGridLayout

你可以通过useRef存储Highcharts实例实现跨回调传递,具体修改如下:

核心修改逻辑

  • 用useRef声明持久化存储容器:ref的更新不会触发组件重渲染,适合存储不需要响应式更新的第三方实例对象
  • 在HighchartsReact的callback回调中将实例存入ref,替代原有无效的return逻辑
  • 调整onResizeStop回调逻辑,直接从ref中读取已存储的chart实例调用reflow方法,注意react-grid-layout的onResizeStop原生参数不包含chart对象,原有入参写法是错误的。

完整修改后代码

import { Responsive, WidthProvider } from 'react-grid-layout';
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import { useRef } 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) => {
    // 声明存储chart实例的ref
    const chartRef = useRef(null);
    const layout1 = [
        { i: "1", x: 0, y: 0, w: 8, h: 8 },
    ]

    const handleResize = () => {
        // 加非空判断避免实例未初始化时报错
        if(chartRef.current) {
            chartRef.current.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 }
                        // 将chart实例存入ref
                        callback = { chart => { chartRef.current = chart; }}
                    />
                </div>
            </ResponsiveGridLayout>
        </div>
    )
}

export default Blocks

内容的提问来源于stack exchange,提问作者Nishant Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:24:01