
React Plockは、驚くべき開発者エクスペリエンスを備えた驚くべきメーソンリーレイアウトを作成できるツリーシェービング可能なウルトラスモールNPMパッケージ( 1KB GZIPT未満)です。 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です。
configプロパティの列属性に配列を渡す場合は、要素の数は、提供されるメディアの数とギャップブレークポイントに等しくなければならないことに注意してください!
// 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 ] ,
} }
/ >