简体   繁体   中英

Using react useRef() --why my ref is null?

I have a simple example

function Node() {
    const [hidden, setHidden] = useState(true);
    const inputRef = useRef(null)
    console.log(inputRef);
    return (
        <div>
            {!hidden && <h2 ref={inputRef}>Hello World</h2>}
            {hidden && <button onClick={() => setHidden(false)}>Show Child</button>}
        </div>
    )
}

Upon clicking the button, I would expect that the h2 DOM element is attached to my ref. However, I found that the ref.current is still null upon logging, but if I expand the object, it contains the DOM node.

How am I supposed to access the DOM element via my ref? At the time I want to reference it, for example inputRef.current.getBoundingClientRect() , it's always shown as null. Your help is much appreciated!

Your ref is not initialize when setHidden set to false if you want to use it you need some interactions like this

        import React, { useRef, useState, useEffect } from 'react';
    
    function App() {
        const [hidden, setHidden] = useState(true);
        const inputRef = useRef(null)
        console.log(inputRef);
        const handleChange=()=>{
        console.log(inputRef);
          
        }

useEffect(()=>{
   console.log(inputRef);
},[hidden])
        return (
            <div>
              <input onChange ={handleChange}></input>
                {!hidden && <h2 ref={inputRef}>Hello World</h2>}
                {hidden && <button onClick={() => setHidden(false)}>Show Child</button>}
            </div>
        )
    }
    
    export default App;

You are trying to use the ref in the render phase, but the ref will be populate once React paint the screen, in the commit phase. So, call it in a useEffect or useLayoutEffect

// run synchronously after all DOM mutations
React.useLayoutEffect(() => {
  // do something with inputRef
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM