react plock
v3.4.0

React Plock是一种可摇晃的超小NPM包装(小于1KB的GZB ),可让您创建具有惊人开发人员体验的惊人砖石布局。使用React Plock,您可以轻松地创建适应不同屏幕尺寸和设备的响应式和可自定义的布局。
npm install react-plock使用新的V3 API使用Plock这是一块小菜。这是如何创建砌体网格的一个示例。您甚至可以通过单击此处查看此示例的演示。
import { Masonry } from 'react-plock' ;
const ImagesMasonry = ( ) => {
const items = [ ... imageUrls ] ;
return (
< Masonry
items = { items }
config = { {
columns : [ 1 , 2 , 3 ] ,
gap : [ 24 , 12 , 6 ] ,
media : [ 640 , 768 , 1024 ] ,
} }
render = { ( item , idx ) => (
< img key = { idx } src = { item } style = { { width : '100%' , height : 'auto' } } />
) }
/>
) ;
} ;React Plock提供了平衡的布局选项,该选项通过考虑每个项目的高度来创建更具视觉和谐的砌体网格。当使用useBalancedLayout: true启用时,布局算法会在列之间分发项目,同时试图最大程度地减少列之间的高度差异。
这对于具有不同高度的内容(例如图像或卡片)特别有用,在这些高度上,传统的砌体布局可能会创建不平衡的列。
与依次分配项目的默认布局不同,平衡的布局动态测量并调整项目位置以创建更加美观的结果。
< Masonry
items = { items }
config = { {
columns : [ 2 , 3 , 4 ] ,
gap : [ 16 , 16 , 16 ] ,
media : [ 640 , 768 , 1024 ] ,
useBalancedLayout : true , // Enable balanced layout
} }
render = { ( item ) => (
< img src = { item . url } alt = { item . alt } style = { { width : '100%' } } />
) }
/>这是砌体组件的打字稿定义,您可以找到更详细的说明。
export type MasonryProps < T > = React . ComponentPropsWithoutRef < 'div' > & {
items : T [ ] ;
render : ( item : T , idx : number ) => React . ReactNode ;
config : {
columns : number | number [ ] ;
gap : number | number [ ] ;
media ?: number [ ] ;
useBalancedLayout ?: boolean ;
} ;
as ?: React . ElementType ;
} ; 该道具接受了一系列元素,每个元素都将传递给渲染属性。
砌体渲染道具。在这里,您可以定义网格的每个瓷砖的样式,该功能采用当前循环项目和相对索引。
用于定义项目之间的列数,媒体查询和差距的配置对象。
如您所见,通过使用React.ComponentPropsWithoutRef<"div">您可以简单地将每个可用属性传递给Div,一些示例是ID和className 。唯一将被覆盖的属性将是style ,因为内部用于砌体一代。
请注意,如果您将数组传递给配置属性的列属性,则元素的数量必须等于提供的媒体和差距断点的数量!
// Correct: This will be responsive with 3 breakpoints.
< Masonry
{ ... otherProps }
config = { {
columns : [ 1 , 2 , 3 ] ,
gap : [ 12 , 16 , 20 ] ,
media : [ 640 , 768 , 1024 ] ,
} }
/>
// Correct: This will be responsive with 2 breakpoints.
< Masonry
{ ... otherProps }
config = { {
columns : [ 1 , 2 ] ,
gap : [ 2 , 4 ] ,
media : [ 640 , 1024 ] ,
} }
/ >
// Correct: This will be fixed with 4 columns in every screen size.
< Masonry
{ ... otherProps }
config = { {
columns : 4 ,
gap : 8
} }
/>
// NOT Correct: This will cause trouble in rendering.
< Masonry
{ ... otherProps }
config = { {
columns : [ 4 ] ,
media : [ 640 , 768 ] ,
} }
/ >