react实现图片轮播
使用 react-slick 实现图片轮播
安装 react-slick 和 slick-carousel
npm install react-slick slick-carousel
基本组件实现
import React from 'react';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
const ImageCarousel = ({ images }) => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000
};
return (
<div style={{ width: '80%', margin: '0 auto' }}>
<Slider {...settings}>
{images.map((img, index) => (
<div key={index}>
<img
src={img}
alt={`slide-${index}`}
style={{ width: '100%', height: '400px', objectFit: 'cover' }}
/>
</div>
))}
</Slider>
</div>
);
};
export default ImageCarousel;
自定义样式和箭头
添加自定义箭头组件

const NextArrow = ({ onClick }) => (
<button
onClick={onClick}
style={{
right: '-25px',
position: 'absolute',
top: '50%',
zIndex: 1,
background: 'transparent',
border: 'none',
fontSize: '24px',
cursor: 'pointer'
}}
>
→
</button>
);
const PrevArrow = ({ onClick }) => (
<button
onClick={onClick}
style={{
left: '-25px',
position: 'absolute',
top: '50%',
zIndex: 1,
background: 'transparent',
border: 'none',
fontSize: '24px',
cursor: 'pointer'
}}
>
←
</button>
);
在 settings 中添加箭头配置
const settings = {
// ...其他设置
nextArrow: <NextArrow />,
prevArrow: <PrevArrow />
};
响应式设计配置
添加响应式断点设置

const settings = {
// ...基础设置
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
dots: false
}
}
]
};
使用 CSS Modules 管理样式
创建样式文件 Carousel.module.css
.container {
width: 80%;
margin: 0 auto;
}
.slideImage {
width: 100%;
height: 400px;
object-fit: cover;
}
.dot {
background: #ccc;
}
.activeDot {
background: #333;
}
更新组件使用 CSS Modules
import styles from './Carousel.module.css';
// 在组件中使用
<div className={styles.container}>
<Slider {...settings}>
{images.map((img, index) => (
<div key={index}>
<img
src={img}
alt={`slide-${index}`}
className={styles.slideImage}
/>
</div>
))}
</Slider>
</div>






