我的 React 应用程序的“关于”页面上有一张图像,我希望该图像每 5 秒更改为新图像。我已经设置了我的钩子,并且我的 aboutImg 状态最初设置为 require('./img/rope.jpg') 来渲染图像。但是当我尝试动态更新它时,我尝试动态添加的每种路径方式都会出现以下错误:
Cannot find module './img/Horseback-riding.jpg'
at webpackEmptyContext (http://localhost:3000/static/js/bundle.js:64374:10)
at http://localhost:3000/static/js/bundle.js:2974:68
我的代码是:
function About() {
const tempImg =['./img/Horseback-riding.jpg','./img/Snowshoeing.jpg','./img/yoga3.3.jpg','./img/rope.jpg']
const [counter, setCounter] = useState(0);
const [aboutImg, setAboutImg] = useState(require('./img/rope.jpg'))
useEffect(() => {
//Implementing the setInterval method
const interval = setInterval(() => {
counter === 3 ? setCounter(0) : setCounter(counter + 1);
setAboutImg(require(tempImg[counter]))
// setCount(count + 1);
}, 5000); // every 5secs it changes
//Clearing the interval
return () => clearInterval(interval);
}, [counter]);
return (
<img src={aboutImg}/>
)
}
export default About;
我已经 consoled.logged aboutImg 并可以看到它显示了正确的字符串,但是当我将变量添加到 require() 中时,它会导致此错误
Webpack 需要在编译时了解所有可能的模块,并且动态地要求带有变量的模块可能会导致问题。
为了解决这个问题,您可以采用不同的方法来动态加载图像。让我知道以下内容是否适合您:
import React, { useState, useEffect } from 'react';
// Import all images
import horsebackRiding from './img/Horseback-riding.jpg';
import snowshoeing from './img/Snowshoeing.jpg';
import yoga from './img/yoga3.3.jpg';
import rope from './img/rope.jpg';
function About() {
const tempImg = [horsebackRiding, snowshoeing, yoga, rope];
const [counter, setCounter] = useState(0);
const [aboutImg, setAboutImg] = useState(tempImg[0]);
useEffect(() => {
const interval = setInterval(() => {
setCounter(prevCounter => (prevCounter === tempImg.length - 1 ? 0 :
prevCounter + 1));
setAboutImg(tempImg[counter]);
}, 5000);
return () => clearInterval(interval);
}, [counter, tempImg]);
return (
<img src={aboutImg} alt="About" />
);
}
export default About;