在DOM更新后运行的React钩子。

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

我有一个React应用,在这个应用中,我根据状态隐藏显示一个元素,并希望在状态变量改变后对该DOM元素进行一些计算。

我试过使用 useLayoutEffect但这仍然是运行 之前 DOM已经更新了,所以我的计算没有用。是不是我对 useLayoutEffect 错了吗?我是不是用错了?

我的情况是这样的

const myComponent = () => {

  const elem = useRef()
  const [isElemVisible, setIElemVisible] = useState(false)

  useLayoutEffect(() => {
    // I want this to run AFTER the element is added/removed from the DOM
    // Instead this is run before the element is actually modified in the DOM (but the ref itself has changed)

    elem.current.getBoundingClientRect() // do something with this object if it exists
  }, [elem.current])


  return (
   <div id="base-element">
    { isElemVisible && (
      <div id="element" ref={elem}></div>
    )}
   </div>
  )
}
javascript reactjs dom react-hooks
1个回答
1
投票

你可以尝试传递一个函数作为ref,并在该函数中做一些事情。

const myComponent = () => {

  // other component code

  const elemRef = useCallback((node) => {
    if (node !== null) {
      // do stuff here
    }
  }, [])


  return (
   <div id="base-element">
    { isElemVisible && (
      <div id="element" ref={elemRef}></div>
    )}
   </div>
  )
}

看看这个 https:/reactjs.orgdocshooks-faq.html#how-can-i-measure-a-dom-node。


0
投票

一个简单的解决方法,就是手动检查状态更新。useEffect 钩。

const myComponent = () => {

  const elem = useRef()
  const [isElemVisible, setIElemVisible] = useState(false)

  useEffect(() => {
   if (isElemVisible) {
     // Assuming UI has updated:
     elem.current.getBoundingClientRect() // do something with this object
   }

  }, [isElemVisible])


  return (
   <div id="base-element">
    { isElemVisible && (
      <div id="element" ref={elem}></div>
    )}
   </div>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.