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

React 16.7中createRef返回current:null的原因及解决咨询

解决React中createRef获取图片clientHeight返回null的问题

嘿,我一眼就揪出问题所在啦——你在img标签里把绑定ref的属性写错了!你用了href={this.imageRef},但href是给<a>标签用的跳转属性,React里要给DOM元素绑定ref,得用ref属性才行。

第一步:修正ref绑定错误

先把PictureForGrid组件里的img标签改对,这是核心问题:

import React from 'react';
class PictureForGrid extends React.Component {
  constructor(props) {
    super(props);
    this.imageRef = React.createRef();
    this.state = {
      imageHeight: 0
    };
  }

  componentDidMount() {
    const imgElement = this.imageRef.current;
    if (imgElement) {
      // 图片加载是异步的,建议监听load事件再获取高度
      imgElement.addEventListener('load', this.handleImageLoad);
      // 处理缓存图片的情况:如果图片已经加载完成,直接触发回调
      if (imgElement.complete) {
        this.handleImageLoad();
      }
    }
  }

  componentWillUnmount() {
    // 移除事件监听,避免内存泄漏
    const imgElement = this.imageRef.current;
    if (imgElement) {
      imgElement.removeEventListener('load', this.handleImageLoad);
    }
  }

  handleImageLoad = () => {
    const realHeight = this.imageRef.current.clientHeight;
    console.log('图片真实高度:', realHeight);
    this.setState({ imageHeight: realHeight });
  }

  render() {
    return (
      <div>
        {/* 把href改成ref!这是最关键的修正 */}
        <img ref={this.imageRef} src={this.props.source} alt={this.props.description} />
      </div>
    )
  }
}
export default PictureForGrid;

为什么还要监听load事件?

你用的React 16.7中,componentDidMount只会在组件DOM挂载完成后执行,但图片资源是异步加载的——DOM挂载了不代表图片已经渲染完毕。如果直接在componentDidMount里获取clientHeight,大概率得到的是0(因为图片还没加载出来)。通过监听图片的load事件,我们能确保在图片完全加载、渲染完成后,获取到真实的高度值。

额外提醒

  • 一定要在componentWillUnmount里移除事件监听,防止组件卸载后还触发回调,造成不必要的内存泄漏。
  • 针对缓存图片的情况,加了imgElement.complete的判断——如果图片已经被浏览器缓存,load事件不会触发,这时候直接调用handleImageLoad就能拿到高度。

这样修改后,你就能正确获取到图片的clientHeight并存入state啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:04:33