如何解决自定义图片库上的图片闪烁
我的组件加载 2 个图像,然后在它们之间设置不透明度以淡入下一个图像。这一切都由 setInterval 介导,该 setInterval 每秒更改图像的索引。
问题在于,在第一张图片转换为第二张图片后,第一张图片会再次短暂显示。这只发生在第一个索引上。我在 Chrome 和 Firefox 上都试过这个,问题在两者上都是一致的。
这是我的代码
import { useEffect } from "react";
import { useState } from "react";
import utils from "../hooks/utils";
const ImageSlider = ({ images,speed = 1000 }) => {
const [current,setCurrent] = useState(0);
const styles = {
slider: {
position: "relative",height: "100vh",display: "flex",},image: {
width: "100vw",objectFit: "cover",animationName: "out",animationTimingFunction: "ease-in-out",animationDuration: `${speed}ms`,zIndex: "2",image2: {
width: "100vw",marginLeft: "-100vw",zIndex: "1",};
useEffect(() => {
const timer = setInterval(() => {
//please remember this in the future
setCurrent((current + 1) % images.length);
},speed);
return () => clearInterval(timer);
});
if (!Array.isArray(images) || images.length == 0) {
return null;
}
return (
<>
<div style={styles.slider}>
{utils.urlArray(images,"",1000).map((image,index,array) => (
<>
{index === current && (
<>
<img
style={styles.image}
src={image}
key={`${index}_${current}_0`}
/>
<img
style={styles.image2}
src={array[(index + 1) % array.length]}
key={`${index}_${current}_1`}
/>
</>
)}
</>
))}
</div>
</>
);
};
export default ImageSlider;
这是我第一次构建这样的组件,所以我似乎无法思考我做错了什么。
谢谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。