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

react-grid-layout布局变化时调用Echarts.resize报错resize is not a function如何解决

问题原因

你触发报错的核心原因是调用resize方法的对象错误:

  • ReactGridLayout的onLayoutChange回调返回的第一个参数是所有grid项的布局配置数组,并非Echarts实例,直接对该数组调用resize()自然会抛出resize is not a function错误。
  • 你没有在父组件统一存储所有Echarts实例,布局变化时无法找到需要调整尺寸的图表对象。
修复步骤

1. 父组件统一存储Echarts实例

在index.js的state中新增字段存储所有图表实例,使用每个图表的唯一key作为键名:

// index.js state初始化
state = {
  // 原有其他state字段
  chartInstances: {}
}

修改子组件回传实例的逻辑,回传时携带当前图表的唯一key,父组件接收后存入state:

// 子组件NewvsReturnVisitors中调用传值方法时增加key参数
props.value(el.key, chartInstance);

// index.js新增接收实例的方法
saveChartInstance = (chartKey, instance) => {
  this.setState(prevState => ({
    chartInstances: {
      ...prevState.chartInstances,
      [chartKey]: instance
    }
  }))
}

2. 重写onLayoutChange回调

布局变化时遍历存储的所有Echarts实例,逐个调用resize方法:

onLayoutChange() {
  Object.values(this.state.chartInstances).forEach(instance => {
    // 增加校验避免实例未初始化完成时报错
    if (instance && typeof instance.resize === 'function') {
      instance.resize()
    }
  })
}

3. 补充适配配置

  • 初始化Echarts时不要写死宽高,改为自适应父容器尺寸
  • grid-item内部包裹Echarts的DOM节点需要设置width: 100%; height: 100%,保证resize可以正确读取容器尺寸
  • 如果布局变化有过渡动画,可以给resize逻辑加100~300ms的防抖,避免频繁调用导致性能损耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:42:01