[英]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.props
或this.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.