用react写个轮播图
时间: 2023-05-12 08:04:15 浏览: 104
好的,以下是一个使用 React 实现的轮播图的示例代码:
```
import React, { useState } from 'react';
const images = [
'https://via.placeholder.com/150',
'https://via.placeholder.com/150',
'https://via.placeholder.com/150',
];
const Carousel = () => {
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const handlePrevClick = () => {
setCurrentImageIndex(currentImageIndex === 0 ? images.length - 1 : currentImageIndex - 1);
};
const handleNextClick = () => {
setCurrentImageIndex(currentImageIndex === images.length - 1 ? 0 : currentImageIndex + 1);
};
return (
<div>
<button onClick={handlePrevClick}>Prev</button>
<img src={images[currentImageIndex]} alt="carousel" />
<button onClick={handleNextClick}>Next</button>
</div>
);
};
export default Carousel;
```
这个轮播图组件接受一个图片数组作为参数,然后在组件内部维护一个 `currentImageIndex` 状态来控制当前显示的图片。当用户点击“Prev”或“Next”按钮时,会更新 `currentImageIndex` 状态,从而切换到上一张或下一张图片。
阅读全文