[英]ReactJS change background image dynamically doesn't work
I am new to reactJS.我是 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.
我只是写了一个 javascript 来每 5 秒更新一次背景图像,但它不起作用。 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.您将初始索引 0 保存在组件范围之外。 So
index + 1
is always evaluating to 1. Instead of saving the imagePath
in your state, save the index in your state.所以
index + 1
总是评估为 1。而不是将imagePath
保存在您的状态中,而是将索引保存在您的状态中。 Then increment it in tick
.然后在
tick
增加它。 Then reference images[index]
.然后参考
images[index]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.