简体   繁体   中英

ReactJS change background image dynamically doesn't work

I am new to reactJS. I want to create a component to change background images dynamically. I just write a javascript to update background image every 5 seconds but it doesn't work. These images are local images, I want to loop them and display them. Would you please take a look? Thank you very much!

import * as React from 'react';
import * as image from './resources';

const TIME_TICK_PERIOD = 5000;
var images =['resources/yellowstone.jpg','resources/yellowstone2.jpg','resources/yellowstone3.jpg'];

export class BackgroundImage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            index:0
        };
    }

    componentDidMount() {
        this.timerID = setInterval(() => this.tick(), TIME_TICK_PERIOD);
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    tick() {
        let idx = this.state.index;
        if(idx >=images.length-1) {
            this.setState({
                index: 0
            });
        } else {
            this.setState({
                index: idx+1
            })
        }
    }

    render() {
        return (
            <div className="hints-on-home-screen">
                <div
                    style={{
                        position: absolute,
                        backgroundImage: `url(${images[this.state.index]}`)
                    }}
                />
            </div>
        );
    }
}

You are saving your initial index of 0 outside the component scope. So index + 1 is always evaluating to 1. Instead of saving the imagePath in your state, save the index in your state. Then increment it in tick . Then reference images[index] .

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