如何在不更改数据的情况下使 Highcharts React 重绘

how to make Highcharts React redraw without changing data

我需要 highcharts 来调整它的宽度以适应父级的宽度。因此,如果我们在不更改数据的情况下更改父项的宽度,则图表应调整大小。 但是由于数据是一样的,所以不会出现这种情况。

如果我们调整浏览器屏幕的大小似乎可以工作,但这不是我们需要的。

import React, { useState } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min);
}

const LineChart = () => {
  const [width, setWidth] = useState(null);
  const [chartOptions, setChartOptions] = useState({
    xAxis: {
      categories: ['A', 'B', 'C'],
    },
    series: [{ data: [1, 2, 3] }],
  });

  const handleWidth = () => {
    const w = getRandomIntInclusive(100, 500);
    setWidth(w);
  };

  return (
    <div style={{ width }}>
      <HighchartsReact highcharts={Highcharts} options={chartOptions} />
      <button onClick={handleWidth}>change container width</button>
    </div>
  );
};

render(<LineChart />, document.getElementById('root'));

这是一个“不工作”的例子 link:https://stackblitz.com/edit/react-xhcmx4?file=index.js

来自 Highcharts API:

reflow([e])

Reflows the chart to its container. By default, the chart reflows automatically to its container following a window.resize event, as per the chart.reflow option. However, there are no reliable events for div resize, so if the container is resized without a window resize event, this must be called explicitly.

作为解决方案,在 width 更改后调用 reflow 方法。

  useEffect(() => {
    const chart = chartComponent.current?.chart;

    if (chart) chart.reflow(false);
  }, [width]);

现场演示: https://stackblitz.com/edit/react-zydh8m?file=index.js

API参考:https://api.highcharts.com/class-reference/Highcharts.Chart#reflow