【发布时间】:2021-04-14 03:08:59
【问题描述】:
我最近尝试在 Gatsby 中开发一个网站,并且我有一个动画,当图像触发其 onLoad 事件时触发。这在gatsby develop 中运行良好,但是当我这样做时gatsby build onLoad 永远不会触发。
如果我在检查元素中手动更改图像 src 以使其加载新图像,则事件会触发。我猜它与服务器端渲染有关,但我不知道如何在不强制一切渲染客户端的情况下解决这个问题。毕竟图像仍然需要时间来加载,那么为什么 onLoad 不会在构建中触发呢?我怎样才能让它着火?
这里的代码去掉了一些不相关的部分。
import React from 'react';
import * as bannerStyles from './banner.module.css';
import negative_forest from '../images/negative_forest.png';
export default class Banner extends React.Component {
constructor(props) {
super(props);
this.wrapper = React.createRef();
this.img = React.createRef();
this.textContainer = React.createRef();
this.onImgLoad = this.onImgLoad.bind(this);
}
render() {
return <div className={bannerStyles.wrapper} ref={this.wrapper}>
<img onLoad={this.onImgLoad} src={negative_forest} alt="Negative Forest" className={bannerStyles.img} ref={this.img} />
<div className={bannerStyles.textContainer} ref={this.textContainer}>
<h1 className={bannerStyles.text}>Title</h1>
<h2 className={bannerStyles.text}>Subtitle</h2>
</div>
</div>;
}
onImgLoad() {
alert('loaded image');
this.img.current.style.animation = `${bannerStyles.imgfade} 3s linear 0s 1 normal forwards`;
this.textContainer.current.style.animation = `${bannerStyles.textfade} 3s linear 0s 1 normal forwards`;
}
}
编辑:我尝试在不同的浏览器中加载站点,它第一次触发了该事件,但随后没有触发,所以我认为它与缓存有关。我的错。
【问题讨论】:
标签: javascript reactjs