如何在 ReactJS 中创建图片轮播?
图片轮播对于任何 Web 应用来说都至关重要,它可以以良好的用户体验展示多张图片。当我们访问亚马逊 (amazon.com) 或车易拍 (cardekho.com) 等知名网站时,它们都会使用轮播展示图片,因为这些网站需要为每个产品展示多张图片。如果不用轮播而直接显示所有图片,用户将无法正确查看图片,而且看起来很糟糕。
因此,在本教程中,我们将学习在 ReactJS 中创建图片轮播的各种方法。
使用 react-simple-image-slider npm 包
react-simple-image-slider 允许我们在 ReactJS 中创建图片轮播。用户需要在项目目录中执行以下命令下载 npm 包。
npm i react-simple-image-slider
安装 react-simple-image-slider npm 包后,用户可以将其导入应用程序并使用它。
语法
用户可以按照以下语法使用 simpleImageSlider 组件。
<SimpleImageSlider width={690} height={470} images={sliderImages} showNavs={true} />
在上面的语法中,我们使用了 SimpleImageSlider 组件并将一些 props 传递给组件。
示例
在下面的示例中,我们使用 SimpleImageSlider 组件创建了基本的图片轮播。我们将宽度和高度值作为 prop 传递,宽度和高度的数值以像素为单位。此外,我们创建了 sliderImages 对象数组,其中包含 URL 属性。之后,我们将 sliderImages 数组作为 prop 传递给组件。
import React from "react"; import SimpleImageSlider from "react-simple-image-slider"; export default function App() { const sliderImages = [ { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTdUmK6fRPfPQIMyOxUOjiTnR2VYizvkkWUxLhGoVJNobm5Id3fpRhsIGtPj3H06ujPb4&usqp=CAU", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcQduUpBWhSdgkWqqIrSmw5MMU697Xlx3SCjlB4eZSv0Q&s", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTnzApyh1ZmbXLBUg_iFRio23hzRyAJfwBRfnVozXdEnu-NK4jFt2_gsYujKf-CbT6Cr_A&usqp=CAU", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTDnfOIY9gjVyoT4ulMp55roiV5KefqaDByUc0HdD8p3tdpXuwxTaXjhLdyUFeQzZ2ZwE&usqp=CAU", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcR3IVlvufXIDZXxq0O8SVqwU2HeO6y7as0OXJl-YT55BA&s", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcQs_7aafRRY4vEbWz2wydowaogMmGI7mRVG6MQfZVtKDFXUGqt5iF-Mu0AYMQBEeznPkU&usqp=CAU", }, { url: "https://smartslider3.com/wpcontent/uploads/2019/01/photo_slideshow.jpg", }, ]; return ( <div> <h3> {" "} Creating the image slider using the react-simple-image-slider </h3> <SimpleImageSlider width={500} height={250} images={sliderImages} showNavs={true} /> </div> ); }
输出
示例
SimpleImageSlider 组件接受各种 props 来定制图片轮播。在这里,我们传递了 showBullets prop 来在下面的轮播中显示项目指示器。showNav prop 用于显示左右箭头。autoPlay prop 允许我们自动切换图片轮播,并且我们还设置了自动播放持续时间。此外,每当图片轮播切换时,我们都会调用回调函数并更新幻灯片编号。
import React, { useState } from "react"; import SimpleImageSlider from "react-simple-image-slider"; export default function App() { const [imageNum, setImageNum] = useState(1); const sliderImages = [ { url: "https://img.freepik.com/free-photo/wide-angle-shot-singletree-growing-clouded-sky-during-sunset-surrounded-by-grass_181624-22807.jpg", }, { url: "https://thumbs.dreamstime.com/b/lone-tree-meadow-sunriseidyllic-fabulous-landscapes-39659821.jpg", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcSprPgYofGmXXPfuEDcZ_XI294n0bME5dTX9TGvINmPiA&s", }, { url: "https://i.pinimg.com/474x/81/ca/47/81ca47eaae35615ba9a9bb57560aaa3c.jpg", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTof2fniv0mZzN8DByLmb6ILU4MvV_SGr_wptMeAut_dPaYMBkeHnHhD5egzU7MB0GSqE&usqp=CAU", }, ]; return ( <div> <h3> {" "} Creating the image slider using the react-simple-image-slider </h3> <SimpleImageSlider width={500} height={250} images={sliderImages} showBullets={true} showNavs={true} autoPlay={true} onStartSlide = {(index, length) => { setImageNum(index); }} autoPlayDelay = {3} /> <div style = {{ fontSize: "1.5rem" }}> The current image slide No is {imageNum}. </div> </div> ); }
输出
从零开始在 ReactJS 中创建图片轮播
本节将教我们从零开始创建图片轮播。在这里,我们将创建 prevSlide() 和 nextSlide() 函数来更改轮播中的图片。
在开始之前,用户需要在 React 项目中安装 Material UI 库,因为我们将使用其中的箭头图标。
npm install @mui/material @emotion/react @emotion/styled
语法
用户可以按照以下语法更改 ReactJS 轮播中的图片幻灯片。
const nextSlide = () => { setCurrent(activeImageNum === length - 1 ? 0 : activeImageNum + 1); }; const prevSlide = () => { setCurrent(activeImageNum === 0 ? length - 1 : activeImageNum - 1); };
在上面的语法中,activeImageNum 变量跟踪轮播中当前图片的位置。nextSlide() 函数根据 activeImageNum 的当前值更改 activeImageNum 变量的值。prevSlide() 函数将 activeImageNum 变量的值减 1。
示例
文件名 – App.Js
在下面的文件中,我们添加了箭头图标来导航轮播中的图片。我们使用了 Material UI 中的箭头图标。当用户点击左箭头时,我们将调用 prevSlide() 函数;当用户点击右箭头图标时,我们将调用 nextSlide() 函数。
在 HTML 部分,我们检查幻灯片的索引是否等于 activeImageNum;仅显示图片;否则隐藏图片。
import React from "react"; import { useState } from "react"; import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos"; import ArrowForwardIosIcon from "@mui/icons-material/ArrowForwardIos"; import "./App.css"; export default function App() { const sliderImages = [ { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTdUmK6fRPfPQIMyOxUOjiTnR2VYizvkkWUxLhGoVJNobm5Id3fpRhsIGtPj3H06ujPb4&usqp=CAU", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcQduUpBWhSdgkWqqIrSmw5MMU697Xlx3SCjlB4eZSv0Q&s", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTnzApyh1ZmbXLBUg_iFRio23hzRyAJfwBRfnVozXdEnu-NK4jFt2_gsYujKf-CbT6Cr_A&usqp=CAU", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcTDnfOIY9gjVyoT4ulMp55roiV5KefqaDByUc0HdD8p3tdpXuwxTaXjhLdyUFeQzZ2ZwE&usqp=CAU", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcR3IVlvufXIDZXxq0O8SVqwU2HeO6y7as0OXJl-YT55BA&s", }, { url: "https://encryptedtbn0.gstatic.com/images?q=tbn:ANd9GcQs_7aafRRY4vEbWz2wydowaogMmGI7mRVG6MQfZVtKDFXUGqt5iF-Mu0AYMQBEeznPkU&usqp=CAU", }, { url: "https://smartslider3.com/wpcontent/uploads/2019/01/photo_slideshow.jpg", }, ]; const [activeImageNum, setCurrent] = useState(0); const length = sliderImages.length; const nextSlide = () => { setCurrent(activeImageNum === length - 1 ? 0 : activeImageNum + 1); }; const prevSlide = () => { setCurrent(activeImageNum === 0 ? length - 1 : activeImageNum - 1); }; if (!Array.isArray(sliderImages) || sliderImages.length <= 0) { return null; } return ( <div> <h2> {" "} Creating the image slider from scratch in ReactJS </h2> <section className = "image-slider"> <div class = "left"> <ArrowBackIosIcon onClick = {prevSlide} /> </div> <div class="right"> <ArrowForwardIosIcon onClick = {nextSlide} /> </div> {sliderImages.map((currentSlide, ind) => { return ( <div className={ind === activeImageNum ? "currentSlide active" : "currentSlide"} key={ind} > {ind === activeImageNum && <img src={currentSlide.url} className="image" />} </div> ); })} </section> </div> ); }
文件名 – App.css
.image-slider { position: relative; height: 400px; display: flex; justify-content: center; align-items: center; } .image { width: 450px; height: 300px; border-radius: 12px; } .left { position: absolute; left: 3rem; top: 50%; font-size: 1rem; color: blue; z-index: 5; cursor: pointer; user-select: none; } .right { position: absolute; right: 3rem; top: 50%; font-size: 2rem; color: blue; z-index: 5; cursor: pointer; user-select: none; } .currentSlide { transition-duration: 0.5s ease; opacity: 0; } .currentSlide.active { opacity: 1; transition-duration: 0.5s; transform: scale(1.2); } h2 {text-align: center;}