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> 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> Upload </button> }
额外注意
你原代码里button的type属性写错了,是button不是butto,如果不修正可能会导致表单默认提交的异常问题。
内容的提问来源于stack exchange,提问作者Mr. Hankey
相关产品推荐
相关产品推荐

