在 DOM 更新后运行的 React hook

Ada*_*son 4 javascript dom reactjs react-hooks

我有一个 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>
  )
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以尝试将函数作为 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>
  )
}
Run Code Online (Sandbox Code Playgroud)

看看这个https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node