index.js 4.5 KB
Newer Older
周宏民's avatar
周宏民 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * @Title:数据列表轮播组件
 * @Author: hongmye
 * @Date: 2023-02-08 16:03:42
 */
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React, { useEffect, useRef, useState } from 'react';
import 'swiper/components/navigation/navigation.min.css';
import 'swiper/components/pagination/pagination.min.css';
import SwiperCore, { Autoplay, Navigation, Pagination } from 'swiper/core';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/swiper.min.css';
import styles from './index.less';
SwiperCore.use([Autoplay, Pagination, Navigation]);

17 18 19 20 21 22 23 24 25 26
const DataCarousel = ({
  list,
  itemHeight,
  gap,
  renderItem,
  renderGap,
  config,
  autoplay,
  onSwiper,
}) => {
周宏民's avatar
周宏民 committed
27
  const contentRef = useRef(null);
28
  const swiperRef = useRef(null);
周宏民's avatar
周宏民 committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  const [colNum, setColNum] = useState(0);
  const [listData, setListData] = useState([]);
  const [height, setHeight] = useState('100%');
  const spliceArr = (arr, num) => {
    let reArr = [];
    arr.map((item) => {
      if (!reArr[reArr.length - 1] || reArr[reArr.length - 1].length === num) {
        // 新行添加
        reArr.push([]);
      }
      if (reArr[reArr.length - 1].length !== num) {
        // 长度不够则直接添加
        reArr[reArr.length - 1].push(item);
      }
      return null;
    });
    return reArr;
  };
  useEffect(() => {
    if (contentRef.current) {
      // 计算每页能显示多少行数据
      const _Height = contentRef.current.offsetHeight;
      const item_height = itemHeight + gap;
      const num = Math.floor((_Height + gap) / item_height);
      setHeight(item_height * (num - 1) + itemHeight);
      setColNum(num || 1);
    }
  }, [contentRef.current?.offsetHeight, itemHeight, gap]);
  useEffect(() => {
    if (colNum) {
59 60 61 62 63 64 65 66 67
      const arr = spliceArr(list, colNum) || [];
      if (swiperRef.current) {
        if (arr.length > 1 && autoplay * 1) {
          swiperRef.current.autoplay.start();
        } else {
          swiperRef.current.autoplay.stop();
        }
      }
      setListData(arr);
周宏民's avatar
周宏民 committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    }
  }, [list, colNum]);
  return (
    <div
      className={classNames(styles.dataCarousel, 'dataCarousel')}
      style={{ width: '100%', height: '100%' }}
      ref={contentRef}
    >
      <div
        className={classNames(styles.dataCarouselSwiper)}
        style={{ width: '100%', height: height }}
      >
        {listData && listData.length ? (
          <Swiper
            slidesPerView={1}
            autoplay={
84
              autoplay * 1 && listData.length > 1
周宏民's avatar
周宏民 committed
85 86 87 88 89 90
                ? {
                    delay: listData.length > 1 ? autoplay : false,
                    disableOnInteraction: false,
                  }
                : false
            }
周宏民's avatar
周宏民 committed
91
            height={height + 2} // 加2是解决第二页顶部有少量显示的问题
周宏民's avatar
周宏民 committed
92 93 94 95
            loop
            direction="vertical"
            onSlideChange={(e) => {}}
            onSwiper={(swiper) => {
96
              swiperRef.current = swiper;
97
              onSwiper && onSwiper(swiper);
周宏民's avatar
周宏民 committed
98 99 100 101
              //鼠标悬浮暂停效果
              swiper.$el[0].addEventListener('mouseover', () => swiper.autoplay.stop());
              //鼠标移开后继续自动滚屏效果
              swiper.$el[0].addEventListener('mouseleave', () => {
102
                listData.length > 1 && autoplay * 1 ? swiper.autoplay.start() : '';
周宏民's avatar
周宏民 committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
              });
            }}
            {...config}
          >
            {listData.map((item, index) => (
              <SwiperSlide key={index} virtualIndex={index} onClick={() => {}}>
                {item.map((i, iIndex) => (
                  <div key={iIndex}>
                    {renderItem(i, index * colNum + iIndex)}
                    {colNum - 1 > iIndex ? (
                      renderGap ? (
                        renderGap()
                      ) : (
                        <div style={{ height: gap }}></div>
                      )
周宏民's avatar
周宏民 committed
118 119 120
                    ) : (
                      <div style={{ height: '2px' }}></div>
                    )}
周宏民's avatar
周宏民 committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
                  </div>
                ))}
              </SwiperSlide>
            ))}
          </Swiper>
        ) : null}
      </div>
    </div>
  );
};

DataCarousel.defaultProps = {
  itemHeight: 40,
  gap: 10,
  renderItem: () => {},
  renderGap: null,
  list: [],
  config: {}, // swiper参数
  autoplay: 3000,
};

DataCarousel.propTypes = {
  itemHeight: PropTypes.number,
  gap: PropTypes.number,
  renderItem: PropTypes.func,
  renderGap: PropTypes.func,
  list: PropTypes.array,
  config: PropTypes.object,
  autoplay: PropTypes.number,
};

export default DataCarousel;