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

React访问ref属性报Cannot read property of undefined如何解决

错误原因

组件首次渲染时,PhotoFileHandler还没完成挂载,profilePicRef.current此时是undefined,直接访问.preview属性就会抛出类型错误。

解决方案

方案1:使用可选链操作符(推荐,ES2020+支持)

直接把条件判断改写为可选链写法,当current为undefined时表达式会直接短路,不会继续访问后续属性:

<PhotoFileHandler ref={profilePicRef} />
{
  profilePicRef.current?.preview !== null &&
  <button className="button is-primary is-outlined" type="button" 
    onClick={() => { 
      onClickUpload(profilePicRef); 
      setActiveModal(''); 
    }}>
    <i className="fas fa-file-image"></i>&nbsp;Upload
  </button>
}

方案2:分层判断(兼容老版本JS环境)

如果项目环境不支持可选链语法,可以先判断current是否存在,再判断preview的值:

<PhotoFileHandler ref={profilePicRef} />
{
  profilePicRef.current && profilePicRef.current.preview !== null &&
  <button className="button is-primary is-outlined" type="button" 
    onClick={() => { 
      onClickUpload(profilePicRef); 
      setActiveModal(''); 
    }}>
    <i className="fas fa-file-image"></i>&nbsp;Upload
  </button>
}

额外注意

你原代码里button的type属性写错了,是button不是butto,如果不修正可能会导致表单默认提交的异常问题。


内容的提问来源于stack exchange,提问作者Mr. Hankey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:42:03