繁体   English   中英

如何在 React 中每 X 秒更改一次背景图像?

[英]How to make the background image change every X seconds in React?

最终编辑:

请参阅下面的工作代码:

 import React, { Component } from 'react'; var images = [ "https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx", "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg" ] class App extends Component { constructor(props) { super(props); this.state = { imgPath: "url(" + images[1] + ")" }; } componentDidMount() { this.interval = setInterval(() => { this.setState({ imgPath: "url(" + images[0] + ")" }) }, 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <div className="App"> <div className='dynamicImage' style={{ backgroundImage: this.state.imgPath }} > {console.log(this.state.imgPath)} </div> </div > ); } }


原始线程:

我正在尝试使用 setInterval() 每 X 秒动态更改图像。

我只是不明白 setInterval 应该放在代码中的什么位置,或者它的输出应该是什么。

我目前的代码是:

 import React, { Component } from 'react'; // Paths to my images var images = [ "https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx", "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg" ] var imgPath = "url(" + images[1] + ")" // Set original value of path function f1() { imgPath = "url(" + images[0] + ")" // Change path when called ? } class App extends Component { render() { setInterval(f1, 500); // Run f1 every 500ms ? return ( <div className="App"> <div className='dynamicImage' style={{ backgroundImage: imgPath }} > // Change background image to one specified by imgPath </div> </div > ); } } export default App;

当前代码输出第一个 imgPath 的 URL,但未能将其更新为函数 f1 中指定的 URL。 据我所知,函数 f1 似乎确实在运行,因为删除它或设置未定义的变量确实会返回错误。 我只是无法改变imgPath。

关于我做错了什么,或者我如何改进我的代码的任何想法?

干杯

编辑:注释代码+删除不必要的行

我会将您的所有变量移动到您的组件中,并且正如 Akash Salunkhe 建议的那样,使用 componentDidMount 来 setInterval。 不要忘记在组件卸载时清除间隔。

这个答案也适用于使用任意数量的图像。

class App extends React.Component {
    constructor(props) {
      super(props);

      const images = [
        "https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
        "https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
        "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
      ];

      this.state = {
        images,
        currentImg: 0
      }
    }

    componentDidMount() {
      this.interval = setInterval(() => this.changeBackgroundImage(), 1000);
    }

    componentWillUnmount() {
      if (this.interval) {
        clearInterval(this.interval);
      }
    }

    changeBackgroundImage() {
      let newCurrentImg = 0;
      const {images, currentImg} = this.state;
      const noOfImages = images.length;

      if (currentImg !== noOfImages - 1) {
        newCurrentImg = currentImg + 1;
      }

      this.setState({currentImg: newCurrentImg});
    }

    render() {
      const {images, currentImg} = this.state;
      const urlString = `url('${images[currentImg]}')`;

      return (
        <div className="App">
          <div className='dynamicImage' style={{backgroundImage: urlString}} >
          </div>
        </div >
      );
    }
  }

你可能想使用this.propsthis.state来存储imgPath ,否则 React 不知道你已经改变了任何东西。

将图像路径放入 state 和 componentDidMount 中,使用 setInterval 并在其中使用 setState 更改图像路径。

@Anurag 是正确的。 您需要在componentDidMount使用setInterval并确保如果您希望渲染方法重新渲染,请调用this.setState 这当然需要您将图像路径存储在this.state

您需要使用 componentDidMount() React Lifecycle 方法来注册您的 setInterval 函数。

这是一个工作示例

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

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      images: [
        "https://picsum.photos/200/300/?image=523",
        "https://picsum.photos/200/300/?image=524"
      ],
      selectedImage: "https://picsum.photos/200/300/?image=523"
    };
  }

  componentDidMount() {
    let intervalId = setInterval(() => {
      this.setState(prevState => {
        if (prevState.selectedImage === this.state.images[0]) {
          return {
            selectedImage: this.state.images[1]
          };
        } else {
          return {
            selectedImage: this.state.images[0]
          };
        }
      });
    }, 1000);

    this.setState({
      intervalId
    });
  }

  componentWillUnmount() {
    clearInterval(this.state.intervalId);
  }

  render() {
    return (
      <div className="App">
        <img src={this.state.selectedImage} alt={"images"} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


您可以更改代码并在此处找到现场演示: https : //codesandbox.io/s/0m12qmvprp

您可以创建与此类似的无限循环,您可能想要使用一组图像 url 并为此编写一些逻辑。 但是正如你所看到的,我为函数setImage()创建了一个无限循环:

  constructor(props) {
    super();

    this.state = {
      image1: props.imageUrls[0],
      image2: props.imageUrls[1],
      changeImage: true
    };

    this.setImage();
  }

  setImage() {
    setTimeout(() => {
      this.setState({ changeImage: !this.state.changeImage }, this.setImage());
    }, 3000);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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