首页 > 解决方案 > 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

任何帮助将不胜感激。

标签: javascriptreactjsasync-awaitreact-hooksuse-state

解决方案


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值的变化。


推荐阅读