【问题标题】:How to show previous image in react in image slider?如何在图像滑块中显示以前的图像?
【发布时间】:2017-07-24 05:33:27
【问题描述】:

我正在尝试在反应中制作图像滑块。我可以制作滑块。如果您单击 next 按钮,它将显示下一张图像。但是当我单击 previous 按钮时,我遇到了一个问题 在上一个按钮上,它不显示上一个图像。 这是我的代码 https://codesandbox.io/s/PNzqkxgPl

import React, { Component } from "react";
import "./listing.css";
const pics = [
  "http://mumbaimirror.indiatimes.com/thumb/msid-59722654,width-320,height-385,resizemode-4.cms",
  "http://mumbaimirror.indiatimes.com/thumb/msid-59719574,width-320,height-385,resizemode-4.cms",
  "https://cdn.pixabay.com/photo/2017/07/14/17/44/frog-2504507__480.jpg",
  "https://cdn.pixabay.com/photo/2016/09/04/13/08/bread-1643951__480.jpg"
];
class Hello extends Component {
  constructor(props) {
    super(props);

    const idxStart = 0;
    this.state = {
      index: idxStart,
      next: this.getNextIndex(idxStart),
      move: false
    };
    this.next = this.next.bind(this);
    this.pre = this.pre.bind(this);
  }

  getNextIndex(idx) {
    if (idx >= pics.length - 1) {
      return 0;
    }
    return idx + 1;
  }

   getPreviousIndex(idx) {
    if (idx >= 0) {
      return pics.length - 1;
    }
    return idx - 1;
  }
  next() {
    this.setState({
      move: true
    });
    setTimeout(() => {
      this.setState({
        move: false
      });
      this.setIndexes(this.getNextIndex(this.state.index));
    }, 500);
  }
  pre() {
    this.setState({
      move: true
    });
    setTimeout(() => {
      this.setState({
        move: false
      });
      this.setIndexes(this.getPreviousIndex(this.state.index));
    }, 500);
  }
  setIndexes(idx) {
    this.setState({
      index: idx,
      next: this.getNextIndex(idx)
    });
  }

  render() {
    const move = this.state.move ? "move" : "";

    return (
      <div>
        <div className="mask">
          <div className="pic-wrapper">
            <div className={`current pic ${move}`}>
              {this.state.index}
              <img src={pics[this.state.index]} alt="" />
            </div>
            <div className={`next pic ${move}`}>
              {this.state.next}
              <img src={pics[this.state.next]} alt="" />
            </div>
          </div>
        </div>
        <button onClick={this.next}>Next</button>
        <button onClick={this.pre}>pre</button>
      </div>
    );
  }
}

export default Hello;

我使用了以下概念。

  • 我总是拍两张照片。一张是current,第二张是next。如果我 单击next 按钮我将current 图像left 移动到0px 下一张图片留给100。 任何更新

【问题讨论】:

    标签: javascript reactjs react-native react-router react-redux


    【解决方案1】:
      getPreviousIndex(idx) {
        if (idx >= 0) { // this should be if (idx === 0)
          return pics.length - 1;
        }
        return idx - 1;
      }
    

    你还需要一个向左滑动的动画:)

    HTH。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-25
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多