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

Recharts图表因无关状态变更重绘后空白问题求助

解决Recharts柱状图重绘后空白的问题
  • 核心问题是ResponsiveContainer和BarChart的尺寸设置冲突,加上父容器可能无明确尺寸,导致重绘时图表尺寸计算异常。

具体修复步骤:

  1. 删掉BarChart组件上的width和height属性,ResponsiveContainer已经负责自适应尺寸,重复设置会打乱尺寸计算逻辑。
  2. 给ResponsiveContainer的父容器设置明确的宽高(比如固定高度300px、宽度100%),确保100%的尺寸有参考基准,避免重绘后容器塌陷。
  3. 可选:给ResponsiveContainer添加minWidth/minHeight,防止极端情况下容器尺寸变为0。

修改后的代码示例:

// 给父容器设置明确尺寸
<div style={{ width: '100%', height: 300 }}>
  <ResponsiveContainer width="100%" height="100%">
    <BarChart
      data={data}
      margin={{
        top: 5,
        right: 30,
        left: 20,
        bottom: 5,
      }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="country" />
      <YAxis />
      <Tooltip itemStyle={{ color: '#000000' }} />
      <Legend />
      <Bar dataKey="value" fill="#8884d8" />
    </BarChart>
  </ResponsiveContainer>
</div>

额外说明:

如果问题仍存在,可尝试用useMemo缓存data,避免组件重绘时不必要的数据重新计算,但这个场景下主要问题还是尺寸冲突。

内容的提问来源于stack exchange,提问作者Vedant Shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:03:31