Owa*_*ais 6 javascript reactjs react-redux
我想使用反应钩子在反应功能组件中获取图像的高度。
我使用了以下代码:
import React, { useRef, useEffect } from 'react'
const DepthChartContent = props => {
  const ref = useRef()
  useEffect(() => {
    if (ref && ref.current && ref.current.clientHeight) {
      console.log('called')
    }
    console.log('useEffect', {
      ref,
      current: ref.current,
      clientHeight: ref.current.clientHeight,
    })
  }, [])
  return (
    <img
      ref={ref}
      className="depth-reference-bar"
      src={DepthRuler}
      alt="no ruler found"
    />
  )
}
这样做的问题是它返回 clientHeight 为 0,但 useEffect 中的 console.log 具有正确的 clientHeight,如下图所示。
这意味着ref && ref.current && ref.current.clientHeight在调用时未定义,但在同一 useEffect 中的安慰显示 的正确值ref,current: ref.current但为零clientHeight: ref.current.clientHeight。
同样,我不能使用....}, [ref && ref.current && ref.current.clientHeight]inuseEffect因为useEffect不接受复杂的表达式。如果我在外部或内部定义了一个变量useEffectas const clientHeight = (ref && ref.current && ref.current.clientHeight) || 0,那么运气不好!
任何人都可以在这方面提供帮助。谢谢!
正如其他人在这里提到的,在大多数情况下,您的逻辑发生在图像加载之前。所以你必须在图像加载后获取图像尺寸,因为浏览器在此之前不知道图像尺寸。
我知道你提到你想用钩子来做,但除非你做的是可重用的东西,否则这里可能不需要钩子。或者除非你想更好地理解它们,否则没关系。
一种选择是只onLoad在图像元素上使用事件。这样,如果您在ref.current或 is 中有东西,您就不必进行所有这些检查img.complete === true。
import React from 'react'
const DepthChartContent = props => {
  const handleImageLoad = (event) => {
    // Do whatever you want here
    const imageHeight = event.target.clientHeight;
  }
  return (
    <img
      ref={ref}
      className="depth-reference-bar"
      src={DepthRuler}
      alt="no ruler found"
      onLoad={handleImageLoad}
    />
  )
}
不要误会我的意思,我绝对喜欢钩子,但它们并不总是解决方案。
| 归档时间: | 
 | 
| 查看次数: | 4730 次 | 
| 最近记录: |