简体   繁体   中英

Return image from React.js function on button click

I am new to React.js and I am trying to create SlideShow....

At first when page loades one image will be loaded (first one in array), then when user clicks left on tag <a> the function slides() should return path from global variable . Images are imported right and they are in array... whenever page loads only first picture is visible and it's impossible to change between images.

What can I do so I can return path to <img> tag so right image would appear?

import bg1 from "../images/bg1.jpg";
import bg2 from "../images/bg2.jpg";
import bg3 from "../images/bg3.jpg";

global.images = [
    bg1, bg2, bg3
];
function slides(n) {
    return(
        global.images[n]
    );
}
<div className="slideShow">
   <img alt="Image" src={slides(0)} className="w-100 h-100"/>
   <a href="" className="prev" onClick={slides(1)}>&#10094;</a>
   <a href="" className="next" onClick={slides(2)}>&#10095;</a>
</div>

You need some way of tracking the active slide number after you can just change the image src

let currentSlide = 0;

let images = ["src1", "src2", "src3"];

function changeSlide(amount) {
  currentSlide += amount;

  currentSlide = currentSlide < 0 ? images.length : currentSlide;

  currentSlide = currentSlide > images.length ? images.length : currentSlide;

  let slideShow = document.getElementById("image");

  slideShow.src = images[currentSlide];
}

changeSlide(1);

changeSlide(-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM