在同构渲染页面中,图片可以在主script.js
文件之前被下载。因此,在react
注册onLoad
事件之前,图像可能已经被加载,从而永远不会触发此事件。
script.js
constructor(props) {
super(props);
this.handleImageLoaded = this.handleImageLoaded.bind(this);
}
handleImageLoaded() {
console.log('image loaded');
}
render() {
return (
<img src='image.jpg' onLoad={this.handleImageLoaded} />
);
}
场景1 - image.jpg
比 script.js
大
在这种情况下一切都正常。事件在图像最终加载之前注册,因此控制台中会显示image loaded
消息。
场景2 - image.jpg
比 script.js
小
在这个场景中您可以看到本文开头描述的问题。 onLoad
事件没有被触发。
问题
我应该怎么做才能在场景2中触发onLoad
事件?
编辑:Soviut的回答实现
为了检测图像在呈现时是否已就绪,您应该检查纯JavaScript img
对象上的complete
属性:
constructor(props) {
super(props);
this.state = { loaded: false };
this.handleImageLoaded = this.handleImageLoaded.bind(this);
this.image = React.createRef();
}
componentDidMount() {
const img = this.image.current;
if (img && img.complete) {
this.handleImageLoaded();
}
}
handleImageLoaded() {
if (!this.state.loaded) {
console.log('image loaded');
this.setState({ loaded: true });
}
}
render() {
return (
<img src='image.jpg' ref={this.image} onLoad={this.handleImageLoaded} />
);
}
node
在后端渲染此 HTML,并带有图像元素。 - EverettsscomponentDidMount
上才会触发事件。 - Everettss