react-masonry-component2
Version:
react 的瀑布流组件库,支持 columns 布局、弹性布局、绝对定位布局三种方法实现
46 lines (43 loc) • 1.88 kB
JavaScript
import { minBy, maxBy } from 'lodash-es';
import React from 'react';
var getListAndHeight = function (_a) {
var _b, _c;
var children = _a.children, columnCount = _a.columnCount, wrapRef = _a.wrapRef, gutter = _a.gutter;
var clientWidth = ((_b = wrapRef === null || wrapRef === void 0 ? void 0 : wrapRef.current) === null || _b === void 0 ? void 0 : _b.clientWidth) || 0;
var cellWidth = (clientWidth - gutter * (columnCount - 1)) / columnCount;
var columns = Array.from({ length: columnCount }).map(function () { return ({
height: 0,
}); });
var list = React.Children.map(children, function (child, index) {
var width = cellWidth;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
var height = (cellWidth / child.props.width) * child.props.height;
if (index < columns.length) {
columns[index].height += height;
return {
node: child,
style: {
width: width,
height: height,
left: index === 0 ? 0 : index * (cellWidth + gutter),
top: 0,
},
};
}
var minColumnIndex = columns.findIndex(function (i) { return i === minBy(columns, function (i) { return i.height; }); });
var top = columns[minColumnIndex].height + gutter;
columns[minColumnIndex].height += height + gutter;
return {
node: child,
style: {
width: width,
height: height,
left: minColumnIndex * (cellWidth + gutter),
top: top,
},
};
});
return { list: list, height: (_c = maxBy(columns, function (i) { return i.height; })) === null || _c === void 0 ? void 0 : _c.height };
};
export { getListAndHeight };