TypeError: ref.current未定义(useRef())

问题描述 投票:0回答:1

我有一个图片,我想存储它的尺寸,以便根据尺寸放置图标。我使用useRef()钩子这样做。

const componentRef=useRef()

然后我添加了这个 componentRef<img ref={componentRef}>. 为了渲染图标,我调用了一个函数 {setIcons}.

return(
  <div>
    <img ref={componentRef}/>
    {setIcons}
  </div>
)

这个函数又是这样的。

const setIcons=(
        props.positions_Reader.map((mac,i)=>(
            <Icon
                style={{
                  position:"absolute",
                  left:componentRef.current.getBoundingClientRect().x,
                  top:componentRef.current.getBoundingClientRect().y
                }}
            />
        ))
    )

错误发生在这一行 left:componentRef.current.getBoundingClientRect().x

在第一次渲染的时候没有错误,但是当我再回去打开组件的时候,就会出现这个错误。有什么建议吗?

reactjs hook jscript use-ref
1个回答
0
投票

问题是,你正试图使用 componentRef 在实际分配之前。利用 useEffect 并将样式存储在状态中,这样就可以保证在重新渲染时 componentRef.current 变化

function App() {
  const componentRef = React.useRef();
  const [style, setStyle] = React.useState({})

  useEffect(() => {
    setStyle({
      left: componentRef.current.getBoundingClientRect().x,
      top: componentRef.current.getBoundingClientRect().y
    })
  }, [componentRef.current])

  const setIcons = props.positions_Reader.map((mac, i) => (
    <Icon
      style={{
        position: "absolute",
        top: style.top + mac.x,
        left: style.left + mac.y
      }}
    />
  ));

  return (
    <div>
      <img ref={componentRef} />
      {setIcons}
    </div>
  );
}

样品演示

© www.soinside.com 2019 - 2024. All rights reserved.