我正在尝试构建一个动态高度网格,在该网格中,我可以将固定高度(100vh)的行数保持在尽可能多的水平,并且不会溢出,每一行的高度都可变,因此我无法计算出要提前适应。
这是我作为原型工作的代码:
.rows-container {
display: flex;
flex-direction: column;
height: 100vh;
width: 100%;
background-color: red;
}
.rows-inner-container {
display: flex;
flex-direction: column;
background-color: orange;
}
import React, { Component } from "react";
import PropTypes from "prop-types";
import "./styles.css";
const data = Array.apply(null, { length: 500 }).map((value, index) => {
return {
data: "Row #" + index
};
});
class DynamicGrid extends Component {
state = {
viewRowsStartIndex: 0,
viewRows: 1,
viewAddRows: true
};
componentDidMount = () => {
this.renderLines();
};
componentDidUpdate = () => {
this.renderLines();
};
renderLines = () => {
let { viewAddRows, viewRows } = this.state;
let containerHeight = this.refs.container.offsetHeight;
let innerContainerHeight = this.refs.innerContainer.offsetHeight;
console.log("HEIGHTS:");
console.log(
"CONTAINER: " +
containerHeight +
" INNER CONTAINER: " +
innerContainerHeight
);
console.log("STATE:");
console.log(
"viewRows: " + viewRows + " - viewAddRows: " + this.state.viewAddRows
);
if (viewAddRows === true && innerContainerHeight < containerHeight) {
this.setState({
viewRows: viewRows + 1
});
} else {
this.setState({
viewAddRows: false,
viewRows: viewRows - 1
});
}
};
getRow = (row, index) => {
let height = Math.floor(Math.random() * 50) + 10;
return (
<div key={index} style={{ height: height }}>
{row.data}
</div>
);
};
getRows = rows => {
let { viewRowsStartIndex, viewRows } = this.state;
let ret = [];
let rowIndex = 0;
for (
let index = viewRowsStartIndex;
index < viewRowsStartIndex + viewRows;
index++
) {
console.log("Processing row " + index);
let row = rows[index];
ret.push(this.getRow(row, rowIndex++));
}
return ret;
};
render() {
let rows = this.getRows(data);
return (
<div ref="container" className="rows-container">
<div ref="innerContainer" className="rows-inner-container">
{rows}
</div>
</div>
);
}
}
export default DynamicGrid;
结果是:
HEIGHTS:
CONTAINER: 630 INNER CONTAINER: 17
STATE:
viewRows: 1 - viewAddRows: true
HEIGHTS:
CONTAINER: 630 INNER CONTAINER: 17
STATE:
viewRows: 2 - viewAddRows: true
HEIGHTS:
CONTAINER: 630 INNER CONTAINER: 17
STATE:
viewRows: 3 - viewAddRows: true
HEIGHTS:
CONTAINER: 630 INNER CONTAINER: 17
STATE:
viewRows: 4 - viewAddRows: true
...
从日志中,我可以看到innerContainer
之后componentDidUpdate
的高度没有得到更新,这是我建立算法的一个假设。
因此,如何在状态更新后获得innerContainer
的新高度,以便用行填充container
?
如果无法执行此操作,如何解决动态高度行的问题?