react-financial-charts生成的SVG超出div边界,在ResponsiveReactGridLayout中如何修复?
修复方案
1. 修正ChartCanvas的参数配置
react-financial-charts的ChartCanvas组件width/height属性对应生成SVG的总宽高,本身已经包含你设置的margin值,不需要额外计算;但你硬编码了ratio={1},在高DPI设备下会导致SVG实际渲染尺寸超出预期,直接删除该参数让组件自动适配设备像素比即可。
调整后的ChartCanvas示例:
return ( <ChartCanvas height={props.height} width={props.width} margin={{ bottom: 50, top: 100, left: 50, right: 50 }} padding={0} seriesName={`OHLCV prices - ${props.coin.coin}`} data={prices} xScale={scaleTime()} xAccessor={xAccessor} xExtents={xExtents} /> )
2. 监听容器尺寸动态更新图表
你当前仅在canvasRef首次挂载时读取一次容器宽高,当ResponsiveReactGridLayout拖拽调整、窗口缩放时容器尺寸变化不会同步更新图表,会导致尺寸不匹配溢出。使用ResizeObserver监听容器尺寸变化,实时更新图表宽高:
修改Home.tsx代码:
import { useState, useEffect, useRef } from 'react'; // 组件内代码 const canvasRef = useRef<HTMLDivElement>(null); const [chartSize, setChartSize] = useState({ width: 0, height: 0 }); useEffect(() => { if (!canvasRef.current) return; // 监听容器尺寸变化 const resizeObserver = new ResizeObserver((entries) => { const { width, height } = entries[0].contentRect; setChartSize({ width, height }); }); resizeObserver.observe(canvasRef.current); return () => resizeObserver.disconnect(); }, []); // 渲染部分 <div key="candlestick" className="home-card" style={{boxSizing: 'border-box'}}> <div ref={canvasRef} style={{ width: "100%", height: "100%", position: 'relative', overflow: 'hidden' }} > {/* 仅当宽高都大于0时渲染图表,避免初始渲染尺寸异常 */} {chartSize.width > 0 && chartSize.height > 0 ? ( <Candlestick coin={coin} width={chartSize.width} height={chartSize.height} /> ) : null} </div> </div>
3. 补充全局样式修复
给home-card类添加盒模型统一配置,避免padding、border占用容器尺寸导致溢出:
.home-card { box-sizing: border-box; width: 100%; height: 100%; } /* 可选:强制图表SVG不超出容器 */ .home-card svg { display: block; max-width: 100%; max-height: 100%; }
内容的提问来源于stack exchange,提问作者Shubhankar Agrawal
相关产品推荐
相关产品推荐

