相当简单的问题,但我的大脑没有点击。在下面非常基本的React组件中,源应该以设定的间隔进行转换和更改。
import React from 'react';
export default React.createClass({
componentDidMount () {
setInterval((function() {
// switch the image source
})(), 5000)
}
render () {
const images = [
"/assets/images/img01",
"/assets/images/img02",
"/assets/images/img03",
"/assets/images/img04",
];
return (
<div id="rotatingImg">
<img src="/assets/images/img01.jpg" />
</div>
)
}
});
答案 0 :(得分:2)
您需要从内部重新渲染组件的东西。改变状态。每次状态更改组件重新渲染。
import React from 'react';
export default React.createClass({
constructor(props) {
super(props);
this.state = {
currentImage: 0
};
}
getRandomImageId() {
const min = 0;
const max = 3;
return Math.floor(Math.random() * (max - min)) + min;
}
componentDidMount () {
setInterval((function() {
this.setState({
currentImage: this.getRandomImageId()
});
})(), 5000)
}
render () {
const images = [
"/assets/images/img01",
"/assets/images/img02",
"/assets/images/img03",
"/assets/images/img04",
];
return (
<div id="rotatingImg">
<img src={images[this.state.currentImage]} />
</div>
)
}
});