React-Google-Charts Sankey图响应式场景适配异常问题求助
React-Google-Charts Sankey图无法自适应侧边栏展开/收起的容器变化
问题描述
我在PrimeReact项目中使用React-Google-Charts的Sankey图,静态场景下图表显示正常,但展开或收起侧边栏时,图表不能自适应容器尺寸变化,要么溢出屏幕要么留白。调整浏览器窗口大小后图表又能恢复正常显示,代码无报错,其他功能正常。
当前使用的代码片段:
<div className="card p-fluid min-w-full"> <h5>Araç Türleri Şeması</h5> <GoogleCharts chartType="Sankey" data={data} width="100%" height="100%" options={optionsSankey} /> </div>
解决思路
Google Charts默认仅监听窗口resize事件触发重绘,但侧边栏展开/收起属于容器内部尺寸变化,不会触发窗口resize事件,因此需要手动触发图表重绘操作。
具体实现方案
方案一:监听PrimeReact侧边栏的状态切换
如果项目使用PrimeReact官方Sidebar组件,可以利用其状态切换事件触发图表重绘:
import { useState, useRef } from 'react'; import { Sidebar } from 'primereact/sidebar'; import { GoogleCharts } from 'react-google-charts'; const SankeyChart = () => { const [sidebarVisible, setSidebarVisible] = useState(false); const chartRef = useRef(null); const handleSidebarToggle = () => { setSidebarVisible(!sidebarVisible); // 延迟重绘,确保容器尺寸已完成更新 setTimeout(() => { chartRef.current?.chart.draw(); }, 100); }; return ( <> <Sidebar visible={sidebarVisible} onHide={handleSidebarToggle} onShow={handleSidebarToggle}> {/* 侧边栏内容 */} </Sidebar> <div className="card p-fluid min-w-full"> <h5>Araç Türleri Şeması</h5> <GoogleCharts ref={chartRef} chartType="Sankey" data={data} width="100%" height="100%" options={optionsSankey} /> </div> </> ); };
方案二:用ResizeObserver监听容器尺寸变化
如果侧边栏没有直接的状态回调,或需要更通用的适配方案,可以使用ResizeObserver监听图表容器的尺寸变化:
import { useEffect, useRef } from 'react'; import { GoogleCharts } from 'react-google-charts'; const SankeyChart = () => { const chartRef = useRef(null); const containerRef = useRef(null); useEffect(() => { const resizeObserver = new ResizeObserver(() => { chartRef.current?.chart.draw(); }); containerRef.current && resizeObserver.observe(containerRef.current); return () => { containerRef.current && resizeObserver.unobserve(containerRef.current); }; }, []); return ( <div ref={containerRef} className="card p-fluid min-w-full"> <h5>Araç Türleri Şeması</h5> <GoogleCharts ref={chartRef} chartType="Sankey" data={data} width="100%" height="100%" options={optionsSankey} /> </div> ); };
注意事项
- 延迟重绘:监听侧边栏状态时添加短延迟,确保DOM尺寸更新完成后再触发重绘,避免无效操作。
- 实例获取:React-Google-Charts组件的
ref可以获取到原生图表实例,调用其draw()方法即可触发重绘。
内容的提问来源于stack exchange,提问作者Emre Demir
相关产品推荐
相关产品推荐

