使用react hooks实现一个轮播图片组件,支持多种轮播模式,支持自定义轮播时间,支持插入视频轮播
时间: 2024-06-09 13:05:16 浏览: 13
好的,以下是一个使用 React Hooks 实现的轮播图片组件:
```jsx
import React, { useState, useEffect, useRef } from 'react';
const Slideshow = ({ images, mode = 'fade', autoplay = true, interval = 3000, video = null }) => {
const [currentIndex, setCurrentIndex] = useState(0);
const [isPaused, setIsPaused] = useState(!autoplay);
const slideshowRef = useRef(null);
const timerRef = useRef(null);
useEffect(() => {
if (!isPaused) {
timerRef.current = setTimeout(() => {
setCurrentIndex((currentIndex + 1) % images.length);
}, interval);
}
return () => clearTimeout(timerRef.current);
}, [currentIndex, isPaused]);
useEffect(() => {
setIsPaused(!autoplay);
}, [autoplay]);
const handlePrev = () => {
setCurrentIndex((currentIndex - 1 + images.length) % images.length);
};
const handleNext = () => {
setCurrentIndex((currentIndex + 1) % images.length);
};
const handleSlideClick = () => {
if (mode === 'slide') {
setIsPaused(true);
setTimeout(() => {
setIsPaused(false);
setCurrentIndex((currentIndex + 1) % images.length);
}, 5000);
}
};
return (
<div className={`slideshow ${mode}`} ref={slideshowRef} onClick={handleSlideClick}>
{images.map((img, idx) => (
<div
key={idx}
className={`slideshow__slide ${currentIndex === idx ? 'active' : ''}`}
style={{ backgroundImage: `url(${img})` }}
>
{video && currentIndex === idx && (
<video className="slideshow__video" src={video} autoPlay muted loop />
)}
</div>
))}
{mode === 'slide' && (
<React.Fragment>
<button className="slideshow__prev" onClick={handlePrev}>
Prev
</button>
<button className="slideshow__next" onClick={handleNext}>
Next
</button>
</React.Fragment>
)}
</div>
);
};
export default Slideshow;
```
该组件支持以下 props:
- `images`:轮播图片数组,每个元素为一个图片 URL。
- `mode`:轮播模式,可选值为 `'fade'` 和 `'slide'`,默认为 `'fade'`。
- `autoplay`:是否自动轮播,可选值为 `true` 和 `false`,默认为 `true`。
- `interval`:轮播时间间隔,单位为毫秒,默认为 `3000`。
- `video`:要插入的视频 URL,当当前轮播图片与该视频对应时,会在该图片上插入该视频。
其中,`mode` 为 `'fade'` 时,使用淡入淡出效果轮播图片;`mode` 为 `'slide'` 时,使用左右滑动效果轮播图片,此时还会显示“Prev”和“Next”按钮,点击可切换图片。
当用户点击轮播图片时,如果当前轮播模式为 `'slide'`,则会暂停轮播 5 秒钟,然后再自动切换到下一张图片。
需要注意的是,该组件使用了 React Hooks,因此需要确保 React 版本不低于 16.8。另外,在使用该组件时,需要先导入该组件,然后将轮播图片数组和其他 props 传递给该组件即可。例如:
```jsx
import Slideshow from './Slideshow';
const images = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
];
const App = () => {
return (
<div>
<Slideshow images={images} mode="slide" autoplay={false} interval={5000} video="https://example.com/video.mp4" />
</div>
);
};
export default App;
```
以上是一个简单的轮播图片组件示例,你可以根据自己的需求进行修改和扩展。