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

如何使用react-rnd拖拽调整容器实现Highcharts图表尺寸自动适配?

实现示例

首先安装所需依赖:

npm install react-rnd highcharts highcharts-react-official

完整组件代码如下:

import React from 'react';
import { Rnd } from 'react-rnd';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

const ResizableHighchart = () => {
  // 存储Highcharts实例引用
  const chartRef = React.useRef(null);

  // 自定义图表配置
  const chartOptions = {
    title: {
      text: '可调整尺寸的折线图'
    },
    xAxis: {
      categories: ['一月', '二月', '三月', '四月', '五月', '六月', '七月']
    },
    series: [
      {
        name: '销量',
        data: [12, 19, 3, 5, 2, 3, 7],
        type: 'line'
      }
    ]
  };

  // 容器尺寸变化时触发图表适配
  const handleContainerResize = () => {
    if (chartRef.current?.chart) {
      // Highcharts内置reflow方法自动适配容器尺寸
      chartRef.current.chart.reflow();
    }
  };

  return (
    <Rnd
      default={{
        x: 50,
        y: 50,
        width: 600,
        height: 400
      }}
      // 可按需添加拖拽尺寸限制
      minWidth={300}
      minHeight={200}
      onResize={handleContainerResize}
    >
      {/* 父容器必须设置宽高100%,铺满Rnd容器区域 */}
      <div style={{ width: '100%', height: '100%' }}>
        <HighchartsReact
          ref={chartRef}
          highcharts={Highcharts}
          constructorType='chart'
          options={chartOptions}
        />
      </div>
    </Rnd>
  );
};

export default ResizableHighchart;

关键说明

  • 必须通过ref获取HighchartsReact组件实例,才能调用内置的reflow()方法触发图表重绘适配
  • 包裹HighchartsReact的div要设置宽高为100%,确保图表默认占满外层可拖拽容器的全部空间
  • reflow()方法会自动读取当前父容器的宽高参数,无需手动计算拖拽后的尺寸传入
  • 可根据业务需求在Rnd组件上配置最小/最大宽高、拖拽范围等限制参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:36:06