设计一种自适应的React卡片列表组件

2020-05-31  本文已影响0人  请叫我Pro大叔

本文介绍一种用React实现的自适应的卡片列表组件,该组件根据卡片的宽度与间隔自动适应不同容器的宽度对卡片进行排列。

接口设计

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
}

实现逻辑

  1. 根据当前浏览器情况计算出卡片和卡片间隔大小
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)
    // ...
}
  1. 获取容器大小
    此处使用的react-resize-detector来监控容器的大小。
const [containerWidth, setContainerWidth] = useState<number>(0)

<ReactResizeDetector
        handleWidth
        onResize={(w: number) => setContainerWidth(w)}
      />
  1. 计算每行所能容纳的卡片数量,并对卡片进行分组
countOfRow = Math.floor(
      (containerWidth + columnGapSize) / (columnSize + columnGapSize)
    )
    rows = countOfRow >= 1 ? group(items, countOfRow) : [items]
  1. 如果支持flexible,重新计算宽度
if (flexible && countOfRow > 0) {
      width =
        (columnSize * containerWidth) /
        ((columnSize + columnGapSize) * countOfRow - columnGapSize)
    }
  1. 调用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>
  1. 补充最后一行的空卡片元素
    由于本方法用flex的justify-content: space-between属性平均分配卡片间隔。因此对最后一行不足的情况,需要进行补充。
{isLastRow(i) &&
            countOfRow > 2 &&
            new Array(countOfRow - 1)
              .fill(1)
              .map((_, k) => <div key={k} style={{ width }} />)}
  1. 样式
.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
}

/**
 * 判断值是否为数值
 * 
 * @param v 值
 */
export const isNumber = (v:any) => typeof v === 'number'

/**
 * 判断值是否为空
 * 
 * @param v 
 */
export const isNull = (v: any) => v === undefined || v === null
*/

注意:useBreakpoint可以使用antd中的useBreakpoint代替。

上一篇 下一篇

猜你喜欢

热点阅读