You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中获取子组件尺寸遇问题,复现Codepen效果受阻

解决React中获取着陆页/元素高度的问题

看起来你在复现Codepen示例时,卡在了获取背景GIF所在着陆页的高度上,而且ref的使用也出了点小问题。我给你梳理下具体的解决步骤,结合你的类组件代码来调整:

第一步:正确绑定Ref(类组件两种方式)

首先你得确保ref正确绑定到目标元素上(也就是背景GIF所在的着陆页容器),类组件里有两种常用的ref方式:

方式1:React.createRef(推荐React 16.3+使用)

先在constructor里初始化ref:

constructor(props) {
  super(props);
  this.state = { height: '' };
  // 初始化ref
  this.Landing = React.createRef();
}

然后在render里,给你的着陆页容器加上ref属性:

render() {
  const { data, scrollClass, height } = this.state;
  return (
    {/* 这里是你的着陆页容器,背景GIF应该在这个元素里 */}
    <div ref={this.Landing}>
      {/* 你的页面内容,比如背景GIF、其他组件 */}
      {data !== ... {/* 你原来的内容 */}}
    </div>
  );
}

方式2:回调Ref(兼容老版本React)

如果你的React版本较低,用回调ref更稳妥:
直接在render的目标元素上写:

<div ref={(element) => this.Landing = element}>
  {/* 你的页面内容 */}
</div>

这种方式不需要在constructor里初始化ref,直接通过回调把元素赋值给this.Landing。

第二步:获取高度并更新state

接下来在componentDidMount里,就能通过ref拿到元素并获取高度了。另外要注意,不同的高度属性对应不同的场景,你可以根据需求选:

  • offsetHeight:包含元素的padding、边框,不包含margin的可见高度
  • clientHeight:包含padding,不包含边框、margin的可见高度
  • scrollHeight:元素内容的总高度(包括滚动后隐藏的部分)

修改你的componentDidMount:

componentDidMount() {
  // 先判断ref是否成功获取到元素
  if (this.Landing.current) { // 对应createRef方式,如果是回调ref就写if(this.Landing)
    const landingHeight = this.Landing.current.offsetHeight;
    this.setState({ height: landingHeight });
    console.log('着陆页高度:', landingHeight);
  }
}

额外:监听窗口resize更新高度

如果你的页面高度会随着窗口大小变化而改变(比如响应式布局),最好加上resize监听,实时更新高度:

componentDidMount() {
  this.getLandingHeight();
  // 添加resize监听
  window.addEventListener('resize', this.getLandingHeight);
}

componentWillUnmount() {
  // 组件卸载时移除监听,避免内存泄漏
  window.removeEventListener('resize', this.getLandingHeight);
}

// 把获取高度封装成一个方法,方便复用
getLandingHeight = () => {
  let landingHeight;
  if (this.Landing.current) { // createRef方式
    landingHeight = this.Landing.current.offsetHeight;
  } else if (this.Landing) { // 回调ref方式
    landingHeight = this.Landing.offsetHeight;
  }
  this.setState({ height: landingHeight });
}

如果要获取整个页面的高度(不是某个元素)

如果你要的是整个浏览器页面的高度,而不是特定元素的高度,那根本不需要ref,直接用原生JS获取:

getPageHeight = () => {
  const pageHeight = Math.max(
    document.documentElement.scrollHeight,
    document.body.scrollHeight,
    document.documentElement.offsetHeight,
    document.body.offsetHeight,
    document.documentElement.clientHeight,
    document.body.clientHeight
  );
  this.setState({ height: pageHeight });
}

这样调整后,你应该就能正确获取到需要的高度啦~

内容的提问来源于stack exchange,提问作者Jaeger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:34:17