我在react中写了一个网格布局组件。在网格内部,我已经加载了高图表,它工作得很好。在调整网格的宽度和高度时,高图表不会调整大小,并且在调整大小时会断开。我搜索了堆栈溢出,在这里的"Resize highcharts using react-grid-layout not working“中发现了同样的问题。然后我才知道,当网格布局发生变化时,将调用chart reflow方法来使高位图表适合网格。因为我是一个新的反应,我不知道如何使它成为可能。帮我想出一些解决方案。
下面是我尝试过的代码:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import '/home/paulsteven/Documents/resize-ui/resize_ui/node_modules/react-grid-layout/css/styles.css';
import '/home/paulsteven/Documents/resize-ui/resize_ui/node_modules/react-resizable/css/styles.css';
import GridLayout from 'react-grid-layout';
import BarChart from "highcharts-react-official";
class MyFirstGrid extends React.Component {
state ={
options :{reflow:true,
title: {
text: 'Fruit Consumption'
},
subtitle: {
text: 'Steven Chart'
},
chart: {
type: 'bar'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Prince',
data: [4, 4, 2]
}, {
name: 'Syed',
data: [5, 3, 5]
},
{
name: 'Sam',
data: [1, 3, 3]
}]
}
}
render() {
// layout is an array of objects, see the demo for more complete usage
var layout = [
{i: 'a', x: 0, y: 0, w: 5, h: 2},
{i: 'b', x: 1, y: 0, w: 3, h: 2},
{i: 'c', x: 4, y: 0, w: 1, h: 2}
];
return (
<GridLayout className="layout" layout={layout} cols={12} rowHeight={30} width={1200}>
<div style={{backgroundColor: 'grey'}} key="a">
{/* <div id="container" style={{width:'100%',height:'400px'}}></div> */}
<BarChart options ={this.state.options} />
</div>
<div style={{backgroundColor: 'red'}}key="b">b</div>
<div style={{backgroundColor: 'blue'}} key="c">c</div>
</GridLayout>
)
}
}
export default MyFirstGrid;发布于 2021-03-12 10:50:54
我认为调整高分辨率的功能不起作用的原因可以从the documentation of 'reflow' from hightcharts中找到
默认情况下,图表会根据the chart.reflow option在a window.resize event之后自动重排到其容器。但是,div resize没有可靠的事件,因此如果在没有窗口resize事件的情况下调整容器的大小,则必须显式调用此事件。
这种情况与您现在所做的情况相匹配:您试图调整div本身的大小,但没有调整窗口大小,因此它不能按您预期的那样工作。
我做了什么使我的图表在网格中可调整大小,如下所示:
const onLayoutChange = () => {
for (let i = 0; i < Highcharts.charts.length; i += 1) {
if (Highcharts.charts[i] !== undefined) {
Highcharts.charts[i].reflow(); // here is the magic to update charts' looking
}
}
};使用react-grid-layout提供的onLayoutChange的
<GridLayout
cols={12}
layout={layout}
rowHeight={30}
width={1200}
onLayoutChange={() => onLayoutChange()}
>
...
</GridLayout>还有then...BANG!您可以通过react-grid-layout中的调整大小按钮来控制可调整大小的图表。
为了便于理解,您可以在此处查看实时工作:https://codesandbox.io/s/resize-highcharts-in-grid-9e625?file=/src/App.js
https://stackoverflow.com/questions/57265992
复制相似问题