每当 <img src={value} /> src 值更改时触发动画



我使用React创建一个img元素,该元素在特定时间后根据包含许多图像的数组使用setInterval函数更改其src属性。

所以事情是我想做一个动画每当src属性的变化,我正在考虑使用React.useEffect()挂钩观看src的变化,并添加一些动画,但我不能走得更远的逻辑。

my code:

import Canada from "../images/Canada.jpg"
import Tokyo from "../images/Tokyo.jpg"
import NewYork from "../images/NewYork.jpg"
import southKorea from "../images/southKorea.jpg"

function AboutMe() {
const imgArray = [NewYork, Tokyo, Canada, southKorea]
let i = 0;
const maxImgArray = imgArray.length -1 ;
const swap = function() {
let image = imgArray[i];
i = (i === maxImgArray) ? 0 : ++i;
const attr = document.getElementById("moving-image");
attr.src=image;
}
setInterval(swap, 5000)
return (
<section className="About-me">
<h1>About me</h1>
<div className="container">
<div className="cities-images">
<img 
src={Tokyo}
alt="NewYork" id="moving-image"></img>
<label class="switch">
<input type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div className="info">

</div>
</div>
</section>    
)
}

通过在react中使用useState钩子,我们可以用更新后的值重新渲染组件。因此,对于src更改,我们可以使用useState来更新图像的当前src。

通过使用useEffect钩子,我们可以在src状态改变时做任何事情,比如设置不同的动画。

组件状态

const [image, setImage] = useState(Usa);
const [imageIndex, setImageIndex] = useState(0);
const imgArray = [Usa, Japan, Canada, SouthKorea];

useEffect

useEffect(() => {
let interval = null;
if (i !== maxImgArray) {
interval = setInterval(() => {
let image = imgArray[imageIndex];
const attr = document.getElementById("moving-image");
attr.src = image;
// update the img index to state
setImageIndex((imageIndex) =>
imageIndex === maxImgArray ? 0 : imageIndex + 1
);
// update the src in state.
setImage(attr.src);
}, 3000);
}
// When our code runs and reruns for every render, useEffect also cleans up after itself using the cleanup function.
// Here we clear the interval to remove the effects that could happen with state change while interval.
return () => clearInterval(interval);
}, [image, imageIndex]); // when image, imageIndex gets change, useEffect will be triggered.
<<p>组件/strong>这里我使用帧动动画
<section className="Country-flag">
<h1>Country Flag</h1>
<div className="container">
<motion.div
key={image}
animate={{ x: 100, opacity: 1 }}
transition={{
delay: 1,
x: { type: "spring", stiffness: 100 },
default: { duration: 2 }
}}
>
{/* when state {image} value change, this component will re-render with new src */}
<img alt="NewYork" src={image} id="moving-image"></img>
</motion.div>
<div className="info"></div>
</div>
</section>

检查此示例沙箱以查看生成的代码。

如果您想为每个图像添加不同的动画,那么为动画添加另一个状态变量,并更改每个图像状态的useEffect中的值。

相关内容

最新更新