index.js 2.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
/*
 * @Title:数据列表轮播组件
 * @Author: hongmye
 * @Date: 2023-02-08 16:03:42
 */
import PandaEmpty from '@wisdom-components/empty';
import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import 'swiper/components/navigation/navigation.min.css';
import 'swiper/components/pagination/pagination.min.css';
import SwiperCore, { Autoplay, Mousewheel, 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, Mousewheel]);

const DataCarousel = ({ list, itemHeight, renderItem, config, autoplay, onSwiper, showEmpty = true }) => {
  const autoplayConfig = {
    delay: autoplay,
    disableOnInteraction: false,
  };
  const contentRef = useRef(null);
  const swiperRef = useRef(null);
  const [listData, setListData] = useState([]);

  useEffect(() => {
    setListData(list);
  }, [list]);
  return (
    <div
      className={classNames(styles.dataCarousel, 'dataCarousel')}
      style={{ width: '100%', height: '100%' }}
      ref={contentRef}
    >
      <div className={classNames(styles.dataCarouselSwiper)} style={{ width: '100%', height: '100%' }}>
        {listData && listData.length ? (
          <Swiper
            slidesPerView="auto"
            autoplay={autoplay * 1 && listData.length > 1 ? autoplayConfig : false}
            loop
            height={itemHeight}
            direction="vertical"
            onSlideChange={e => {}}
            mousewheel
            onSwiper={swiper => {
              swiperRef.current = swiper;
              onSwiper && onSwiper(swiper);
              // 鼠标悬浮暂停效果
              swiper.$el[0].addEventListener('mouseover', () => swiper.autoplay.stop());
              // 鼠标移开后继续自动滚屏效果
              swiper.$el[0].addEventListener('mouseleave', () => {
                listData.length > 1 && autoplay * 1 ? swiper.autoplay.start() : '';
              });
            }}
            {...config}
          >
            {listData.map((item, index) => (
              <SwiperSlide key={index} virtualIndex={index} onClick={() => {}}>
                {renderItem(item, index + 1)}
              </SwiperSlide>
            ))}
          </Swiper>
        ) : showEmpty ? (
          <div style={{ paddingTop: 10 }}>
            <PandaEmpty />
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default DataCarousel;