reactjs - 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>
);
}
}
解决方案
仅当代码在浏览器中运行时尝试包含 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>
);
}
}
推荐阅读
- javascript - 样式化组件生产上的空 cssrulesets
- javascript - 如何在任意点的给定半径内找到所有标记/特征并存储所述标记的纬度/经度?
- python - 我没有在 python django 中迁移
- kubernetes - AKS 未创建 KUBERNETES_SERVICE_HOST 和 KUBERNETES_SERVICE_PORT 环境变量
- microsoft-graph-api - 与多个团队/组重复使用传出的 webbook?
- typo3 - 避免在中间表中存储数据时的 TYPO3 后端工作流程
- html - 使用 Bootstrap 在导航栏上方添加顶栏
- javascript - 如何等待用户在 J-Query 文本字段中按下回车键?
- android - 打开带有文件路径android 11的相机意图不起作用
- python - pywinauto 后端“uia”未注册!问题