我在我的应用程序中使用 ResponsiveGridLayout、React-Grid-Layout,并且我使用 echarts 作为网格项。
拖放工作正常,但是当我调整网格项目的大小时,图表并没有一起调整大小。我已经尝试实现 onLayoutchange 属性,但它不起作用。
有人可以帮我吗
这是我重现问题的代码框
我在我的应用程序中使用 ResponsiveGridLayout、React-Grid-Layout,并且我使用 echarts 作为网格项。
拖放工作正常,但是当我调整网格项目的大小时,图表并没有一起调整大小。我已经尝试实现 onLayoutchange 属性,但它不起作用。
有人可以帮我吗
这是我重现问题的代码框
我能够做到这一点,至少在修改网格项目的宽度(还不是高度......)时,通过使用这个钩子,然后在你的图表组件中:
[...]
const chartRef = useRef<HTMLDivElement>();
const size = useComponentSize(chartRef);
useEffect(() => {
const chart = chartRef.current && echarts.getInstanceByDom(chartRef.current);
if (chart) {
chart.resize();
}
}, [size]);
[...]
return <div ref={chartRef}></div>;
...所以当网格项目调整大小时,您的图表将调整大小。我不确定,对我来说仍然是 WIP,但它有效。
您可以useEchartResizer.ts
根据@rehooks/component-size创建:
import useComponentSize from '@rehooks/component-size';
import * as echarts from 'echarts';
import React, { useEffect } from 'react';
export const useEchartResizer = (chartRef: React.MutableRefObject<HTMLDivElement>) => {
const size = useComponentSize(chartRef);
useEffect(() => {
const chart = chartRef.current && echarts.getInstanceByDom(chartRef.current);
if (chart) {
chart.resize();
}
}, [chartRef, size]);
};
然后在保存图表的组件中使用它:
export const ComponentWithChart = (props): React.ReactElement => {
const chartRef = useRef<HTMLDivElement>();
useEchartResizer(chartRef);
useEffect(() => {
const chart = echarts.init(chartRef.current, null);
// do not set chart height in options
// but you need to ensure that the containing div is not "flat" (height = 0)
chart.setOption({...} as EChartsOption);
});
return (<div ref={chartRef}></div>);
});
所以每次调整 div 的大小时,useEchartResizer
都会触发一个chart.resize()
. 适用于 react-grid-layout。