Appearance
Masonry 瀑布流布局
基本使用
TIP
使用 JS 贪心算法 + Flex 分列布局,目前前端界(包括小红书 web 端)最成熟、性能最好、且不会乱跳的方案
tsx
tsx
import { Masonry } from "@lite-code/shared";
import { create } from "@lite-code/reactive";
export const createItem = (key: number) => ({
key,
height: Math.floor(Math.random() * (300 - 50) + 50), // 随机高度 50-300
style: {
backgroundColor: `hsl(${Math.random() * 360}, 70%, 80%)`,
},
content: <span style={{ color: "#333" }}>item: {key + 1}</span>,
});
const store = create({
items: Array.from({ length: 12 }).map((_, i) => createItem(i)),
});
export default () => {
const snap = store.useSnapshot();
return (
<>
<Masonry items={snap.items} style={{ padding: 10 }} columnCount={4} />
<a
type="primary"
style={{ marginTop: 10 }}
onClick={() => {
store.items.push(
...Array.from({ length: 10 }).map((_, i) =>
createItem(snap.items.length + i)
)
);
store.items = [...store.items];
}}
>
添加元素
</a>
</>
);
};