小程序里没有 CSS columns / masonry 的原生支持,两列瀑布流只能靠「数据分列 + 预计算高度」模拟。
分列算法本身只有十行,真正的知识点是高度从哪来:接口给原始宽高最稳,其次是 image 的 load 事件,最后才是不稳定的渲染后测量。
单位也是一坑——宽度交给 flex 自适应,高度却要写成 rpx,两套基准混用就会错位。
这篇按「量列宽 → 分列 → 渲染」走一遍,并修掉原稿里几个让分列失效的写法。
背景
文件在 pages/img/fallWater.tsx,样式在 styles/index.scss 的 .fallWaterFlexWrap。
需求:图片高度不一,按「谁矮接谁」自动分到左右两列。数据里预先带好原始宽高(模拟接口返回),这样首屏就能算出高度,不会出现「先挤在一起再撑开」的跳动。
数据结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| type Photo = { id: number width: number height: number image: string desc: string displayHeight?: number col?: 'left' | 'right' }
const imageItems: Photo[] = [ { id: 0, width: 683, height: 1024, image: 'https://example.com/1.png', desc: '愿我如星君如月,夜夜流光相皎洁。' }, ]
|
源码开头那段关于「高度从哪来」的注释值得原样保留:
实现
1. 先量列宽,再换算高度
原稿把基准写死成 200(item.height * 200 / item.width),但列宽实际由 flex 分配,跟 200 毫无关系;而且宽度是 %、高度是 rpx,200 到底是 px 还是 rpx 也没交代。改成实测列宽并换算成 rpx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const GAP_RPX = 16
const measureColWidth = () => new Promise<number>((resolve) => { createSelectorQuery() .select('#item0') .boundingClientRect((rect) => { if (!rect || Array.isArray(rect)) { resolve(0) return } resolve((rect.width * 750) / getWindowInfo().windowWidth) }) .exec() })
|
#item0 是左列容器,即使还没有子元素也有宽度,所以首屏就能量到,不依赖数据渲染完成。
2. 分列:谁矮接谁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const createWaterfall = (colWidthRpx: number) => { let leftHeight = 0 let rightHeight = 0 const left: Photo[] = [] const right: Photo[] = []
imageItems.forEach((item) => { const displayHeight = (item.height * colWidthRpx) / item.width
if (leftHeight <= rightHeight) { leftHeight += displayHeight + GAP_RPX left.push({ ...item, displayHeight, col: 'left' }) } else { rightHeight += displayHeight + GAP_RPX right.push({ ...item, displayHeight, col: 'right' }) } })
setLeftList(left) setRightList(right) }
|
『累计高度比较 → 短的一列接新图』:这是两列瀑布流的标准解,时间复杂度 O(n),不需要预先知道总高度。
3. 量已有两列高度(加载更多用)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const colHeightRef = useRef({ left: 0, right: 0 })
const getColHeights = () => { for (let i = 0; i < 2; i++) { createSelectorQuery() .select(`#item${i}`) .boundingClientRect((rect) => { if (!rect || Array.isArray(rect)) return if (i % 2 === 0) { colHeightRef.current.left = rect.height } else { colHeightRef.current.right = rect.height } }) .exec() } }
|
.exec() 不能漏——boundingClientRect 只是登记查询,exec 才真正发出。
4. 串起来
1 2 3 4 5 6 7 8 9 10
| const [leftList, setLeftList] = useState<Photo[]>([]) const [rightList, setRightList] = useState<Photo[]>([])
useEffect(() => { if (!imageItems.length) return measureColWidth().then((colWidthRpx) => { if (!colWidthRpx) return createWaterfall(colWidthRpx) }) }, [imageItems])
|
注意顺序:先量宽,再分列。boundingClientRect 是异步的,拿不到同步返回值,所以分列逻辑只能写在它的回调 / then 里。
5. 渲染
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <View className="fallWaterFlexWrap"> <View className="flex-1 flex flex-col h-fit mr-10" id="item0"> {leftList.map((item) => ( <View className="border-2 rounded-md h-fit mb-20" key={item.id}> <Image src={item.image} mode="widthFix" style={{ width: '100%', height: `${item.displayHeight}rpx` }} /> <View className="py-8 px-2 text-center flex flex-col"> <View>Title: 示例{item.id}-left</View> <View>Desc: {item.desc}</View> </View> </View> ))} </View>
<View className="flex-1 flex flex-col h-fit" id="item1"> {rightList.map((item) => ( <View className="border-2 rounded-md h-fit mb-20" key={item.id}> <Image src={item.image} mode="widthFix" style={{ width: '100%', height: `${item.displayHeight}rpx` }} /> <View className="py-8 px-2 text-center flex flex-col"> <View>Title: 示例{item.id}-right</View> <View>Desc: {item.desc}</View> </View> </View> ))} </View> </View>
|
6. 样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| .fallWaterFlexWrap { display: flex; flex-wrap: wrap; padding: 10rpx 20rpx; justify-content: space-between; background-color: #fff; }
|
留 grid 版本是有原因的:grid 做不到「列内高度累加」(grid-auto-flow 是按行填充),所以最终换成 flex + 手动分列。
踩坑
h-fit 不能省:容器高度取内容高度,不加的话某一列会被拉满整屏、另一列空一截。
- 高度与宽度必须同一套基准:宽度交给 flex(
%),高度用实测列宽换出来的 rpx。写死一个 200 的基准,换个机型就整体错位。
- 累计高度一定要初始化:
let leftHeight = 0,从状态对象或上一次的 undefined 上取,NaN 会让所有比较静默失效。
- 别改写源数据:换算结果放到新字段,否则重排一次就再放大一次。
- 异步测量的顺序:
boundingClientRect 必须 .exec() 才执行,回调里也拿不到同步结果,所以「先量宽再分列」是有时序依赖的。
- **加载更多时不要从头
forEach**:应从测得的 colHeightRef 续接,增量 push;每次都从头分列会导致已渲染内容跳动。原稿注释里也写了「目前没有处理动态情况」,这是它明确的边界。
- 闪烁:靠
image 的 load 事件取高度,首屏必然「先挤在一起再撑开」;接口返回原始宽高才是最优解。