【问题标题】:Changing an Image on in time interval using react使用反应在时间间隔内更改图像
【发布时间】:2019-07-19 07:33:24
【问题描述】:

我正在尝试更改每 1 秒显示的图像,第一个图像出现然后切换到 alt 显示并且不继续切换图片

export default class Slideshow extends Component {

    constructor(props) {
        super(props);
        this.getImageId = this.getImageId.bind(this);
        this.switchImage = this.switchImage.bind(this);
        this.init = this.init.bind(this);
        this.state = {
            currentImage: 0,
            image: 0

        };
    }

    getImageId() {
        if(this.currentImage < 3) {
            this.setState({
                currentImage: this.state.currentImage +1
            })
        } else {
            this.setState({
                currentImage: 0
            })
        }
        return this.currentImage;
    }

    switchImage() {
            this.setState({
                image: this.getImageId()
            });
    }

    init() {
        setInterval(this.switchImage, 1000)
    }


    render() {
        const imagePath = [guy, girl, wash, swifer];
        this.init();

        return (
            <div className="slideshow-container">
                <img src={imagePath[this.state.image]} alt="cleaning images"/>      
            </div>
        );
    }
}

图片每1秒切换到数组中的下一张图片,遍历整个数组后返回原始图片

【问题讨论】:

  • 嗨,贾斯汀,我刚刚在下面为您提供了一个解决方案,它应该让您对如何集成此功能有足够的了解。如果您有任何问题,请告诉我,请考虑投票并将其标记为答案:)

标签: javascript html arrays reactjs setinterval


【解决方案1】:

试试这样的:https://codesandbox.io/s/naughty-sara-q3m16

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.switchImage = this.switchImage.bind(this);
    this.state = {
      currentImage: 0,
      images: [
        "https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
        "https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MzAvb3JpZ2luYWwvc2h1dHRlcnN0b2NrXzExMTA1NzIxNTkuanBn",
        "https://d17fnq9dkz9hgj.cloudfront.net/uploads/2012/11/152964589-welcome-home-new-cat-632x475.jpg",
        "https://i.ytimg.com/vi/jpsGLsaZKS0/maxresdefault.jpg"
      ]
    };
  }

  switchImage() {
    if (this.state.currentImage < this.state.images.length - 1) {
      this.setState({
        currentImage: this.state.currentImage + 1
      });
    } else {
      this.setState({
        currentImage: 0
      });
    }
    return this.currentImage;
  }

  componentDidMount() {
    setInterval(this.switchImage, 1000);
  }

  render() {
    return (
      <div className="slideshow-container">
        <img
          src={this.state.images[this.state.currentImage]}
          alt="cleaning images"
        />
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我们可以通过做几件事来简化您的代码:

  1. 将图像数组置于状态,以便我们可以迭代 图像路径并跟踪当前图像索引。
  2. 所以现在我们可以将switchImagegetImageId 合并为一个 服务于相同目的的单一功能。我们只是检查 currentImage(索引)对数组的长度。
  3. React 还有一个生命周期方法,叫做componentDidMount() 它在渲染组件后立即执行逻辑 第一次。我用它来替换init() 函数。在render() 中调用init() 存在问题。每次组件重新渲染时,它都会执行render() 中的逻辑,这意味着您将在每次后续重新渲染时创建一个新的setInterval()componentDidMount() 只触发一次,非常适合定义间隔。

【讨论】:

    【解决方案2】:

    您的代码的主要问题是您在渲染函数中调用了 init 函数,每当状态获取更新渲染也执行时,所以每次渲染函数执行时都会一次又一次地调用 init 函数

    解决办法是在componentDidMount函数中设置间隔

    componentDidMount 仅在组件挂载到 DOM 后运行一次,有关 react 生命周期功能的帮助请访问官方文档

    https://reactjs.org/docs/react-component.html

    也看看这个帖子图片

    https://reactjs.org/docs/react-component.html

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      相关资源
      最近更新 更多