在我的代码中,im试图通过使用onLoad通过clientHeight获取div的高度。在这种情况下,ComponentDdiMount不会在div中加载图像时给定clientHeight。代码对我来说很好。但是当我尝试使用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>
);
}
}
答案 0 :(得分:1)
仅当代码在浏览器中运行时,才尝试包含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>
);
}
}
答案 1 :(得分:0)
使用gatsby build
而不是gatsby develop
,在您的代码请求它们时未定义某些对象,例如window
或document
。通过在触发函数之前检查窗口是否在componentDidMount
生命周期/ useEffect
钩中定义,可以修复常见错误。来自Gatsby's documentation:
您的某些代码引用了“浏览器全局变量”,例如
window
或document
。如果这是您的问题,则应该在上面看到类似的错误 “window
未定义”。要解决此问题,请找到有问题的代码,然后 要么a)在调用代码之前检查是否定义了window
,以便 盖茨比(Gatsby)正在构建时代码未运行(请参见下面的代码示例),或者 b)如果代码在React.js组件的render函数中,请移动 该代码进入componentDidMount
生命周期或useEffect
挂钩, 这样可以确保除非在浏览器中,否则代码不会运行。
因此,我的第一种方法是检查window
是否已定义:
load = () =>{
let centerHeight;
if (typeof window !== undefined){
centerHeight= this.topref.current.clientHeight;
//animate div
}
}
如果这不起作用,我将尝试更改您的onLoad函数,并直接在componentDidMount
中使用它:
export default class Mainpageanimation extends React.Component {
constructor(props) {
super(props);
this.topref = React.createRef();
}
componentDidMount(){
let centerHeight;
if (typeof window !== undefined){
centerHeight= this.topref.current.clientHeight;
//animate div
}
}
render(){
return (
<div className="topdiv" ><img src={require("image.png") } ref={this.topref} /></div>
);
}
}
除了答案,我认为您应该绑定参考。在功能组件中,箭头功能会自动执行,但在像您这样的有状态组件中,您必须手动执行。在您的构造函数中:
this.topref= this.topref.bind(this);
您可以在Refs and the DOM by React documentation中查看更多信息。