gpt4 book ai didi

css - react 虚拟化 : Collection with cells that have the same fixed height but different widths

转载 作者:太空宇宙 更新时间:2023-11-04 09:18:50 27 4
gpt4 key购买 nike

如果我可以使用 React Virtualized 的 Collection 组件来解决我的问题,我有点困惑。我将尝试描述我在做什么:

我在页面上使用 React Virtualized 来显示两个元素列表/集合。我已经完成了第一个包含具有相同宽度和高度的元素的集合:

Collection where cells have same height & width

第一个集合非常简单易行。现在我正在处理第二个集合,其中包含不同大小的图像。我希望单元格具有相同的高度但不同的宽度(当然取决于图像尺寸)。问题是行可能并不总是具有相同数量的单元格:

Collection where cells have same height but different width

这有可能通过 React Virtualized 实现吗?如果是这样,我如何确定“cellSizeAndPositionGetter”中的位置?

最佳答案

我最近使用 react-virtualized List 来显示行固定高度、可变宽度的图像卡片,效果很好。

我的 List rowRenderer 使用图像卡片元素的行数组。即,一个由 React 组件组成的数组,如 JSX。

查看我的最终函数 cardsRows,了解我如何根据元素宽度和屏幕宽度构建行。

这是它的样子:

List rows layout

希望这对您有所帮助!

我的一些代码片段:

import {AutoSizer, List} from 'react-virtualized';

...

updateDimensions() {
this.setState({
screenWidth: window.innerWidth,
});
}

componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
}


componentDidUpdate(prevProps, prevState) {
const props = this.props;
const state = this.state;

if (JSON.stringify(props.imageDocs) !== JSON.stringify(prevProps.imageDocs) || state.screenWidth !== prevState.screenWidth)
this.setState({
cardsRows: cardsRows(props, state.screenWidth),
});
}


rowRenderer({key, index, style, isScrolling}) {
if (!this.state.cardsRows.length)
return '';
return (
<div id={index} title={this.state.cardsRows[index].length} key={key} style={style}>
{this.state.cardsRows[index]}
</div>
);
}

...

render() {
return (
<div style={styles.subMain}>
<AutoSizer>
{({height, width}) => (<List height={height}
rowCount={this.state.cardsRows.length}
rowHeight={164}
rowRenderer={this.rowRenderer}
width={width}
overscanRowCount={2}
/>
)}
</AutoSizer>
</div>
);
}

...

const cardsRows = (props, screenWidth) => {

const rows = [];
let rowCards = [];
let rowWidth = 0;
const distanceBetweenCards = 15;

for (const imageDoc of props.imageDocs) {
const imageWidth = getWidth(imageDoc);

if (rowWidth + distanceBetweenCards * 2 + imageWidth <= screenWidth) {
rowCards.push(cardElement(imageDoc));
rowWidth += distanceBetweenCards + imageWidth;
}
else {
rows.push(rowCards);
rowCards = [];
rowWidth = distanceBetweenCards;
}
}
if (rowCards.length) {
rows.push(rowCards);
}
return rows;
};


const styles = {
subMain: {
position: 'absolute',
display: 'block',
top: 0,
right: 0,
left: 0,
bottom: 0,
}
};

关于css - react 虚拟化 : Collection with cells that have the same fixed height but different widths,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41610200/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com