ReactJS: изменить отображаемое текущее изображение с помощью кнопок назад и вперед

Я работаю над проектом на ReactJS. Я пытаюсь изменить текущее изображение, отображаемое в изображении, с помощью кнопок «Назад» и «Далее». Однако функциональность кнопки не работает должным образом. Вот код.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import  Header  from "./Header.js"
import "../sass/home.css"
import MCLogo from "./MCLogo.png"
import DNA from "./DNA.jpg"
import ES1 from "./EnviroSample1.jpg"
import AP1 from "./AntiBioProducer1.jpg"
import BDLogo from "./BDLogo.png"
import { runInThisContext } from 'vm';
class Home extends Component{
constructor(props)
{
    super(props);
    this.state = {

        images: [require("./DNA.jpg"), require("./MCLogo.png")],
        currentIndex: 0

    };
    this.goToPrevSlide = this.goToPrevSlide.bind(this);
    this.goToNextSlide = this.goToNextSlide.bind(this);

}
   goToPrevSlide () {
  //  this.setState(this.state.currentIndex = ((this.state.currentIndex-1)%3));
  const {length} = this.state.images;
  const{currentIndex} = this.state.currentIndex;
  const newPointer = currentIndex === 0 ? length -1 : currentIndex - 1;
  this.setState({currentIndex: newPointer});

}
goToNextSlide ()  {
  //  this.setState(this.currentIndex = ((this.currentIndex+1))%3);
  const {length} = this.state.images;
  const{currentIndex} = this.state.currentIndex;
  const newPointer = currentIndex === length -1 ? 0 : currentIndex + 1;
  this.setState({currentIndex: newPointer});

}
render(){

    return(
        <div className = "home">
                <Header></Header>

                <div className = "logo">
                <img src = {MCLogo} width = "125" height = "100" />
                </div>
                <div className = "blackBox">

                    <div className = "image fade">
                        <img src = {this.state.images[this.state.currentIndex]} width = "300" height = "300"/>

                    </div>
                    <button class = "prev" onclick = {this.goToPrevSlide}>&#10094;</button>
                    <button class = "next" onclick = {this.goToNextSlide}>&#10095;</button>

                    <script>

                    </script>
                </div>
            <h1>
                Welcome to the Antibiotic Producer Database!
            </h1>

            <h2>
                Recent Updates
            </h2>
            <p>
                Nov 17 2018: Reviewed current state of website w/ Charlotte Berkes
            </p>
            <p>
                Oct 17 2018: Confirmed w/ Charlotte Berkes to use Firebase
            </p>
            <p>
                Oct 5 2018: Met with Charlotte Berkes to continue to discuss requirements. 
            </p>

            <p>
                Oct 3 2018: Finished the Requirements Doc.
            </p>
            <p>
                Sep 13 2018: Initial Meeting w/ Charlotte Berkes to discuss the project.
            </p> 
            <h1>
                DISCLAIMER
                </h1> 
                <p>
                    This website is subject to "fair use", which means that there are restrictions on who can do what on the website.
                    All users, regardless of logged in status, are able to view the homepage, blog page and search functionality.
                    Furthermore, they can view all information of samples and producers. However, to add a sample or a producer to the database,
                    they would have to create an account. Only Merrimack students and faculty with a valid @merrimack.edu address are allowed to create an account.
                    If a registered user uses the site innapropriatly, an administrator can delete their account at the user's expense.
                    </p>            
            <h2>
                About the Project
            </h2>
            <p>
                There has been a declining number of Antibiotics being found today. However, recent technologies have let scientists access previously untapped microbial space.
                Merrimack Students under the direction of Charlotte Berkes will challenge this assumption by going around the Merrimack valley by collecting various environmental samples.
                These samples will include plants and soil. Students will then upload information about the samples to the website.
                Additionally, these students will search for microbiomes using antibiotic discovery and upload their findings to the Antibiotic Producer database. 
            </p>

            <p>
                Created By Samuel Bitzer, Mitchell Gent and Nicholas Mirasol. Special thanks to Charlotte Berkes.

            </p>

                <div className = "botlogo">
            <img src = {BDLogo} width  = "200" height = "200"/>
            </div>
            </div>

    );
}
}       

export default Home;

Как это работает не так, как ожидалось? Что происходит, когда вы нажимаете кнопку «Назад» и «Далее»?

Shawn Andrews 19.11.2018 06:28

Изображение на черном ящике остается неизменным независимо от того, какую кнопку вы нажимаете.

Samuel Bitzer 19.11.2018 06:48
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Массив зависимостей в React
Массив зависимостей в React
Все о массиве Dependency и его связи с useEffect.
1
2
1 353
1

Ответы 1

В вашем коде есть несколько ошибок.

  • Используйте onClick вместо onclick
  • Назначение деструктуризации currentIndex было выполнено в обоих обработчиках

И убедитесь, что URL-адрес (src) для изображения отличается, потому что React не будет повторно визуализировать компонент, если в его свойствах или состоянии нет изменений. Надеюсь это поможет!

class App extends React.Component {
  constructor(){
    super()
    this.images = [
      'https://source.unsplash.com/random/100x100',
      'https://source.unsplash.com/random/120x100',
      'https://source.unsplash.com/random/130x100',
      'https://source.unsplash.com/random/140x100',
      'https://source.unsplash.com/random/150x100',
      'https://source.unsplash.com/random/160x100',
    ]
    this.state = {
      currentIndex: 0,
    }
    this.goToPrevSlide = this.goToPrevSlide.bind(this);
    this.goToNextSlide = this.goToNextSlide.bind(this);

  }
  goToPrevSlide () {
    const {currentIndex} = this.state;
    const newPointer = currentIndex === 0 ? this.images.length -1 : currentIndex - 1;
    this.setState({currentIndex: newPointer});
  }
  
  goToNextSlide ()  {
    const {currentIndex} = this.state;
    const newPointer = currentIndex === this.images.length - 1 ? 0 : currentIndex + 1;
    this.setState({currentIndex: newPointer});
  }
  
  render(){
    return(
        <div className = "home">
          <img src = {this.images[this.state.currentIndex]} width = "300" height = "300"/>
          <br/>
          <button class = "prev" onClick = {this.goToPrevSlide}>&#10094;</button>
          <button class = "next" onClick = {this.goToNextSlide}>&#10095;</button>
          <br/>
          Index {this.state.currentIndex}
        </div>

    );
}

}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id = "app"></div>

Другие вопросы по теме