首页 > 解决方案 > Gatsby 在使用 onLoad 时构建出现窗口错误

问题描述

在我的代码中,我试图通过使用 onLoad 来获取 clientHeight 的 div 高度。在这种情况下,ComponentDdiMount 不会提供 clientHeight,因为图像会加载到 div 中。代码对我来说很好。但是当我尝试 gatsby 构建时,我得到了窗口错误,因为我正在使用 onLoad。有什么解决方法吗?

    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>
      );
    }
   }

标签: reactjsbuildwindowgatsby

解决方案


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

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>
      );
    }
   }


推荐阅读