React 轮播图组件代码示例
以下是一个简单的 React 轮播图组件代码示例:
import React, { useState } from 'react';
const images = [
'https://via.placeholder.com/500x250/ff0000/ffffff',
'https://via.placeholder.com/500x250/00ff00/ffffff',
'https://via.placeholder.com/500x250/0000ff/ffffff'
];
const Carousel = () => {
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const nextImage = () => {
const nextIndex = currentImageIndex === images.length - 1 ? 0 : currentImageIndex + 1;
setCurrentImageIndex(nextIndex);
};
const prevImage = () => {
const prevIndex = currentImageIndex === 0 ? images.length - 1 : currentImageIndex - 1;
setCurrentImageIndex(prevIndex);
};
return (
<div>
<button onClick={prevImage}>Prev</button>
<img src={images[currentImageIndex]} alt='carousel' />
<button onClick={nextImage}>Next</button>
</div>
);
};
export default Carousel;
这个组件使用了 useState hook 来在组件内部保存当前图片的索引。nextImage 和 prevImage 函数用于在点击 'Next' 和 'Prev' 按钮时更新当前图片的索引。渲染函数返回三个元素: 一个按钮用于向后翻页,一个 img 元素显示当前的图片,和一个按钮用于向前翻页。
原文地址: https://www.cveoy.top/t/topic/mwSR 著作权归作者所有。请勿转载和采集!