Gatsby构建在使用onLoad时出现窗口错误 [英] Gatsby build getting window error while using onLoad

查看:141
本文介绍了Gatsby构建在使用onLoad时出现窗口错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,im试图通过使用onLoad通过clientHeight获取div的高度。在这种情况下,ComponentDdiMount不会在div中加载图像时给定clientHeight。代码对我来说很好用,但是当我尝试使用gatsby构建时,使用onLoad会得到窗口错误。

In my code im trying to get the div height by clientHeight by using onLoad. ComponentDdiMount doesnt give the clientHeight in this case as images load in the div.The code works fine for me.But when i try gatsby build i get the window error as im using onLoad. Is there any workaround for this?

    export default class Mainpageanimation extends React.Component {
      constructor(props) {
        super(props);
        this.topref = React.createRef();
      }
      load = () =>{ 
       const centerheight = this.topref.current.clientHeight;
       //animate div
      }
     render(){
       return (
         <div className="topdiv" ><img src={require("image.png") } ref={this.topref}  onLoad= 
    {this.load}/></div>
      );
    }
   }


推荐答案

尝试仅当代码在浏览器中运行时才包括onLoad属性

Try including onLoad property only when the code is running in the browser

export default class Mainpageanimation extends React.Component {
      constructor(props) {
        super(props);
        this.topref = React.createRef();
      }
      load = () =>{ 
       const centerheight = this.topref.current.clientHeight;
       //animate div
      }
     render(){
       return (
         <div 
            className="topdiv" >
            <img src={require("image.png") } ref={this.topref}  
            {...typeof window !== 'undefined' ? {onLoad: this.load} : {}}
            />
         </div>
      );
    }
   }

这篇关于Gatsby构建在使用onLoad时出现窗口错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆