我目前正在循环浏览图像列表,以使灯在条形上的运动动画化。不幸的是,我没有使用CSS,因为在我的设置中,似乎这种循环可能是最好的方法,但是它似乎占用了很多资源,因此我想知道是否有解决方法,还是我只需要更改所有内容。下面是我正在使用的代码:
有关代码的帮助来自此处:
How to loop over images array and render them in a component for React?
代码
state = {
bars:[bar1,bar2,bar3,bar4,bar5],
activeImageIndex: 0
};
componentDidMount(){
setInterval(()=>{
let newActiveIndex = this.state.activeImageIndex===4 ? 0 : this.state.activeImageIndex+1
this.setState({
activeImageIndex: newActiveIndex
})
}, 1000);
}
<Image src={this.state.bars[activeImageIndex]} />
代码运行良好,然后由于似乎占用了更多资源而使应用程序运行缓慢。检查网络工具,我可以看到资源正在增长(文件在我的应用程序中的名称有所不同):
有没有更好的方法来解决这个问题?还是在每次通话后释放资源的方法?
答案 0 :(得分:1)
我是给出回答的人:)
所有带有setInterval加班时间的东西都会减慢速度,尤其是如果您每隔1秒使用javascript修改dom一次,尤其是当它们为图片时。
每次调用setInterval时,浏览器都需要用下一张图像重新绘制容器,该绘制可能会花费很多ms,但是如果花费超过16ms(60fps),则会丢弃帧,并且您的应用程序将开始变得懒惰。
这就是动画之王的原因: CSS
.lightbox {
border: solid 3px black;
display: inline-flex;
padding: 10px 20px;
justify-content: space-between;
width: 200px;
position: relative;
margin-left: 24px;
align-items: center;
}
.light {
border: solid 3px black;
border-radius: 50%;
height: 15px;
width: 15px;
animation: blink 5s linear infinite;
}
.light:nth-child(2) {
animation-delay: 1s
}
.light:nth-child(3) {
animation-delay: 2s
}
.light:nth-child(4) {
animation-delay: 3s
}
.light:nth-child(5) {
animation-delay: 4s
}
@keyframes blink {
0% {
background-color: orangered;
}
19% {
background-color: orangered;
}
20% {
background-color: transparent;
}
100% {
background-color: transparent;
}
}
.lightbox::before,
.lightbox::after {
content: "";
border: solid 1.5px black;
width: 20px;
height: 0;
position: absolute;
}
.li
<div class="lightbox">
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
</div>
该代码段不会随时间推移而变滞,最重要的是,它 不会阻塞线程 。