本文介紹一種用React
實(shí)現(xiàn)的自適應(yīng)的卡片列表組件,該組件根據(jù)卡片的寬度與間隔自動適應(yīng)不同容器的寬度對卡片進(jìn)行排列甩牺。
接口設(shè)計(jì)
type PropertyType = number
/** 支持自適應(yīng)的大小接口 */
interface Size {
xs?: PropertyType
sm?: PropertyType
md?: PropertyType
lg?: PropertyType
xl?: PropertyType
xxl?: PropertyType
}
type SizeType = PropertyType | Size
interface ResponsiveGridProps<T> {
/** 元素?cái)?shù)據(jù)列表 */
items: T[]
/** 卡片寬度 */
size?: SizeType
/** 列最小間隔 */
columnGap?: SizeType
/** 行間隔 */
rowGap?: SizeType
/** 自定義樣式類 */
className?: string
/**
* 是否支持彈性:
* 當(dāng)容器寬度大于所有列最小間隔和列寬時(shí)曹鸠,是否支持列寬同間隙一同放大
*/
flexible?: boolean
/** 元素渲染器 */
renderItem: (item: T) => React.ReactNode
}
實(shí)現(xiàn)邏輯
- 根據(jù)當(dāng)前瀏覽器情況計(jì)算出卡片和卡片間隔大小
function getSize(size: SizeType, screens: ScreenMap) {
if (isNumber(size)) {
return size as number
}
const currSize = size as Size
if (!isNull(currSize.xxl)) {
if (screens.xxl) {
return currSize.xxl!
}
}
if (!isNull(currSize.xl)) {
if (screens.xxl || screens.xl) {
return currSize.xl!
}
}
if (!isNull(currSize.lg)) {
if (screens.xxl || screens.xl || screens.lg) {
return currSize.lg!
}
}
if (!isNull(currSize.md)) {
if (screens.xxl || screens.xl || screens.lg || screens.md) {
return currSize.md!
}
}
if (!isNull(currSize.sm)) {
if (screens.xxl || screens.xl || screens.lg || screens.md || screens.sm) {
return currSize.sm!
}
}
return currSize.xs!
}
function ResponsiveGrid<T>({
items,
size = 280,
columnGap = 24,
rowGap = 24,
className,
renderItem,
flexible = false
}: ResponsiveGridProps<T>) {
// ...
const screens = useBreakpoint()
const columnSize = getSize(size, screens)
// ....
const columnGapSize = getSize(columnGap, screens)
// ...
}
- 獲取容器大小
此處使用的react-resize-detector
來監(jiān)控容器的大小煌茬。
const [containerWidth, setContainerWidth] = useState<number>(0)
<ReactResizeDetector
handleWidth
onResize={(w: number) => setContainerWidth(w)}
/>
- 計(jì)算每行所能容納的卡片數(shù)量,并對卡片進(jìn)行分組
countOfRow = Math.floor(
(containerWidth + columnGapSize) / (columnSize + columnGapSize)
)
rows = countOfRow >= 1 ? group(items, countOfRow) : [items]
- 如果支持flexible彻桃,重新計(jì)算寬度
if (flexible && countOfRow > 0) {
width =
(columnSize * containerWidth) /
((columnSize + columnGapSize) * countOfRow - columnGapSize)
}
- 調(diào)用
renderItem
渲染卡片
<div className={classNames('fs-responsive-grid', className)}>
<ReactResizeDetector
handleWidth
onResize={(w: number) => setContainerWidth(w)}
/>
{rows.map((row, i) => (
<div
key={i}
className="flex justify-between flex-wrap"
style={{ marginTop: i === 0 ? 0 : rowGapSize }}
>
{row.map((item, j) => (
<div key={j} style={{ width }}>
{renderItem(item)}
</div>
))}
</div>
))}
</div>
- 補(bǔ)充最后一行的空卡片元素
由于本方法用flex的justify-content: space-between
屬性平均分配卡片間隔坛善。因此對最后一行不足的情況,需要進(jìn)行補(bǔ)充。
{isLastRow(i) &&
countOfRow > 2 &&
new Array(countOfRow - 1)
.fill(1)
.map((_, k) => <div key={k} style={{ width }} />)}
- 樣式
.flex {
display: flex;
}
.justify-between {
justify-content: space-between;
}
.flex-wrap {
flex-wrap: wrap;
}
完整代碼
// ResponsiveGrid.tsx
import React, { useState } from 'react'
import ReactResizeDetector from 'react-resize-detector'
import classNames from 'classnames'
import { group } from '@/utils/utils'
import { ScreenMap } from '@/utils/responsiveObserve'
import { isNumber, isNull } from '@/utils/types'
import useBreakpoint from '@/components/hooks/useBreakpoint'
type PropertyType = number
interface Size {
xs?: PropertyType
sm?: PropertyType
md?: PropertyType
lg?: PropertyType
xl?: PropertyType
xxl?: PropertyType
}
type SizeType = PropertyType | Size
interface ResponsiveGridProps<T> {
items: T[]
size?: SizeType
columnGap?: SizeType
rowGap?: SizeType
className?: string
flexible?: boolean
renderItem: (item: T) => React.ReactNode
}
function getSize(size: SizeType, screens: ScreenMap) {
if (isNumber(size)) {
return size as number
}
const currSize = size as Size
if (!isNull(currSize.xxl)) {
if (screens.xxl) {
return currSize.xxl!
}
}
if (!isNull(currSize.xl)) {
if (screens.xxl || screens.xl) {
return currSize.xl!
}
}
if (!isNull(currSize.lg)) {
if (screens.xxl || screens.xl || screens.lg) {
return currSize.lg!
}
}
if (!isNull(currSize.md)) {
if (screens.xxl || screens.xl || screens.lg || screens.md) {
return currSize.md!
}
}
if (!isNull(currSize.sm)) {
if (screens.xxl || screens.xl || screens.lg || screens.md || screens.sm) {
return currSize.sm!
}
}
return currSize.xs!
}
function ResponsiveGrid<T>({
items,
size = 280,
columnGap = 24,
rowGap = 24,
className,
renderItem,
flexible = false
}: ResponsiveGridProps<T>) {
const [containerWidth, setContainerWidth] = useState<number>(0)
const screens = useBreakpoint()
const columnSize = getSize(size, screens)
let width = columnSize
let countOfRow = 0
let rows: T[][] = []
// console.log('containerWidth ==> ', containerWidth, width)
if (containerWidth !== 0) {
const columnGapSize = getSize(columnGap, screens)
// console.log('columnGapSize, width ==>', columnGapSize, width)
countOfRow = Math.floor(
(containerWidth + columnGapSize) / (columnSize + columnGapSize)
)
rows = countOfRow > 1 ? group(items, countOfRow) : [items]
if (flexible && countOfRow > 0) {
width =
(columnSize * containerWidth) /
((columnSize + columnGapSize) * countOfRow - columnGapSize)
}
}
// console.log('rows ==> ', rows)
const lastRow = rows.length - 1
const isLastRow = (index: number) => index === lastRow
const rowGapSize = getSize(rowGap, screens)
return (
<div className={classNames('fs-responsive-grid', className)}>
<ReactResizeDetector
handleWidth
onResize={(w: number) => setContainerWidth(w)}
/>
{rows.map((row, i) => (
<div
key={i}
className={`flex flex-wrap ${countOfRow === 1 ? 'justify-center' : 'justify-between'}`}
style={{ marginTop: i === 0 ? 0 : rowGapSize }}
>
{row.map((item, j) => (
<div key={j} style={{ width }}>
{renderItem(item)}
</div>
))}
{isLastRow(i) &&
countOfRow > 2 &&
new Array(countOfRow - 1)
.fill(1)
.map((_, k) => <div key={k} style={{ width }} />)}
</div>
))}
</div>
)
}
export default ResponsiveGrid
/* index.less */
.flex {
display: flex;
}
.justify-between {
justify-content: space-between;
}
.flex-wrap {
flex-wrap: wrap;
}
.justify-center {
justify-content: center;
}
/* utils */
export const group = <T>(arr: T[], countOfPerGroup: number) => {
const groups = []
for (let i = 0; i < arr.length; i += countOfPerGroup) {
groups.push(arr.slice(i, i + countOfPerGroup))
}
return groups
}
/**
* 判斷值是否為數(shù)值
*
* @param v 值
*/
export const isNumber = (v:any) => typeof v === 'number'
/**
* 判斷值是否為空
*
* @param v
*/
export const isNull = (v: any) => v === undefined || v === null
*/
注意:useBreakpoint
可以使用antd中的useBreakpoint
代替眠屎。