javascript - React - 无法获取图片高度/宽度的实际值
问题描述
我正在按照 Udemy 课程制作 Face Recognition React Web 应用程序,但是课程资料已经过时,所以我决定将控制权掌握在我手中并使用钩子和上下文 API 重新构建它。
问题 - 我无法获得上传(获取)图像的实际高度和宽度。尝试了许多不同的方法,但无法使其工作。有时,当图片上传时,我没有得到任何返回它的宽度和高度,有时值没有在“useState”中更新。我需要这些值是正确的,以便将来可以进行计算以从图像中检测人脸。
快速了解这里发生的事情。“useEffect”被用于立即设置“img”状态,它的当前高度和宽度属性=>在 JSX 部分中,“”源是从我的上下文 API 中获取的,而该 API 是从“ImageLinkForm”组件中获取的。
const ImageField = () => {
const faceContext = useContext(FaceContext);
const ref = useRef();
const [img, setImg] = useState({
height: '',
width: ''
});
useEffect(() => {
setImg({ ...img, height: ref.current.clientHeight, width: ref.current.clientWidth })
console.log(`This is height ${img.height}`);
console.log(`This is width ${img.width}`);
}, [faceContext]);
return (
<div className="p-3">
<div className="fieldImg">
<img src={faceContext.fieldUrl} class="img-fluid rounded-lg" id="inputImage" ref={ref} alt="Responsive image" />
<div><h4 className="text-primary">HEADER {img.height}</h4></div>
</div>
</div>
)
}
纸上的这个问题看起来很简单,但我已经坚持了好几个星期了。如果有人愿意从这里看看这里的 github repo - https://github.com/Fruscoqq/FaceRecognition
任何帮助将不胜感激。
解决方案
hook
假设您遇到它无法正常工作,您可以如下所示删除整个。
useEffect(() => {
setImg({ ...img, height: ref.current.clientHeight, width: ref.current.clientWidth })
console.log(`This is height ${img.height}`);
console.log(`This is width ${img.width}`);
}, [faceContext]);
不要ref
像这样传递变量,而是ref={ref}
传递一个ref
回调函数。
ref={onRefChange}
在 func 内部,您可以在元素更改img
时更新状态。DOM
const onRefChange = useCallback(node => {
// ref value changed to node
if (node !== null && node.clientHeight !== null && node.clientWidth !== null) {
setImg({ ...img, height: node.clientHeight, width: node.clientWidth })
}
}, [img]);
我们使用calback refs的原因是因为 React 推荐它来检测ref
值的变化。
推荐阅读
- mysql - 试图重新排列mysql中的数据
- ms-access - 格式化 MS-Access 图表中的轴标签
- python - 通过 python 在 Azure DevOps 中创建工作项
- javascript - 单击按钮时,使用 nextSiblingElement 标签使我的列表项在页面下方
- docker - 在 docker 容器内启动进程时,Sidekiq 日志重定向失败
- matplotlib - 在 matplotlib 中以轴格式将微秒设置为两位小数
- php - 如何按 mmddyyyy 格式的自定义“文本”日期字段排序
- angular - Firebase with Angular:如何计算 Firebase 中嵌套条目的数量
- excel - VBA 从其他工作表复制范围
- javascript - 在 VueJS 中注册 CKEditor 5 时出错