reactjs React中使用Flickity的旋转木马

eanckbw9  于 2023-02-08  发布在  React
关注(0)|答案(2)|浏览(152)

this code可以在React中工作吗?我尝试使用提供的. js文件,但是失败了。你能给我一些关于如何在React中创建这样的carousel的提示吗?

// external js: flickity.pkgd.js
/* external css: flickity.css */

* {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

body { font-family: sans-serif; }

.gallery {
  background: #EEE;
}

.gallery-cell {
  width: 66%;
  height: 200px;
  margin-right: 10px;
  background: #8C8;
  counter-increment: gallery-cell;
}

/* cell number */
.gallery-cell:before {
  display: block;
  text-align: center;
  content: counter(gallery-cell);
  line-height: 200px;
  font-size: 80px;
  color: white;
}
<p><code>wrapAround: true</code></p>

<!-- Flickity HTML init -->
<div class="gallery js-flickity"
  data-flickity-options='{ "wrapAround": true }'>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
</div>
mec1mxoz

mec1mxoz1#

下面是在react中实现它的方式:

import Flickity from 'react-flickity-component'
 
const flickityOptions = {
    initialIndex: 2
}
 
function Carousel() {
  return (
    <Flickity
      className={'carousel'} // default ''
      elementType={'div'} // default 'div'
      options={flickityOptions} // takes flickity options {}
      disableImagesLoaded={false} // default false
      reloadOnUpdate // default false
      static // default false
    >
      <div class="gallery-cell"></div>
      <div class="gallery-cell"></div>
      <div class="gallery-cell"></div>
      <div class="gallery-cell"></div>
      <div class="gallery-cell"></div>
    </Flickity>
  )
}
kzipqqlq

kzipqqlq2#

不需要 Package 器,只需要将flickity作为依赖项安装,就可以动态导入,下面介绍如何在React或Next.js中使用Flickity:

export default function Carousel() {
  
  useEffect(() => {
    initFlickity();
  }, []);

  const carousel = useRef(null);

  async function initFlickity() {
    if (typeof window !== 'undefined' && carousel.current) {
      const Flickity = (await import('flickity')).default;
      new Flickity(carousel.current, {
        lazyLoad: true,
        wrapAround: true,
        autoPlay: true,
      });
    }
  }

  return (
    <div ref={carousel} className="w-full h-[600px] sm:w-[560px] sm:h-auto mx-auto relative">
      <div>
        <img src="/images/slide-1.jpg" />
      </div>
      <div>
        <img src="/images/slide-2.jpg" />
      </div>
    </div>
  );
}

Make sure you set dimensions for your containing element.

相关问题