react写一个轮播图
时间: 2023-10-10 14:13:22 浏览: 114
以下是一个基本的React轮播图组件示例:
```
import React, { useState } from 'react';
const images = [
'https://picsum.photos/id/1018/400/300',
'https://picsum.photos/id/1015/400/300',
'https://picsum.photos/id/1019/400/300'
];
const Carousel = () => {
const [activeIndex, setActiveIndex] = useState(0);
const handlePrevClick = () => {
setActiveIndex(activeIndex === 0 ? images.length - 1 : activeIndex - 1);
};
const handleNextClick = () => {
setActiveIndex(activeIndex === images.length - 1 ? 0 : activeIndex + 1);
};
return (
<div className="carousel">
<div className="carousel-image">
<img src={images[activeIndex]} alt={`Image ${activeIndex}`} />
</div>
<div className="carousel-controls">
<button onClick={handlePrevClick}>Prev</button>
<button onClick={handleNextClick}>Next</button>
</div>
</div>
);
};
export default Carousel;
```
这个组件接收一个`images`数组,表示要轮播的图片列表。它使用`useState`钩子来维护当前活动图片的索引。在`handlePrevClick`和`handleNextClick`函数中,根据当前索引决定下一个索引。最后,它渲染一个包含图片和控件按钮的`div`元素。
阅读全文