简体   繁体   English

使用 react useRef() -- 为什么我的 ref 是 null?

[英]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.单击按钮后,我希望 h2 DOM 元素附加到我的 ref。 However, I found that the ref.current is still null upon logging, but if I expand the object, it contains the DOM node.但是,我在记录时发现 ref.current 仍然是 null,但是如果我展开 object,它包含 DOM 节点。

How am I supposed to access the DOM element via my ref?我应该如何通过我的 ref 访问 DOM 元素? At the time I want to reference it, for example inputRef.current.getBoundingClientRect() , it's always shown as null.当时我想引用它,例如inputRef.current.getBoundingClientRect() ,它总是显示为 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当 setHidden 设置为 false 时,您的 ref 未初始化,如果您想使用它,您需要一些这样的交互

        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.您正在尝试在渲染阶段使用 ref,但是一旦 React 在提交阶段绘制屏幕,就会填充 ref。 So, call it in a useEffect or useLayoutEffect所以,在useEffectuseLayoutEffect中调用它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 React ref element.current 使用 useRef 钩子在 React 组件中返回 null? - Why React ref element.current returns null in React component using useRef hook? React.JS Ref 中的 Ref 错误 - createRef、useRef 和 using Refs - Ref error in React.JS Ref - createRef, useRef, and using Refs react 无法使用 forwardRef 和 useRef 读取 ref 的 null 的属性 - react cannot read properties of null of ref with forwardRef and useRef React Hooks:为什么是.current null for useRef Hook? - React Hooks: Why is .current null for useRef Hook? 为什么在 React 示例中使用 null 初始化 useRef? - Why is useRef initialized with null in React examples? 为什么反应`useRef`钩子将对象存储在`current`属性中? 为什么它不能直接存储在 ref 对象中? - Why react `useRef` hook stores the objects in `current` property? Why cant it store directly in the ref object? React JS ref (useRef):包含不是函数 - React JS ref (useRef): contains is not a function React:为什么从 useRef 更改 ref 的当前值不会在这里触发 useEffect - React: why is that changing the current value of ref from useRef doesn't trigger the useEffect here 为什么在带有 useRef 钩子的 React 组件中切换 div 上的 ref 元素上不可用 clientHeight 或 offsetHeight - Why clientHeight or offsetHeight not available on ref element on toggled div in React component with useRef hook 在 React 中使用 useRef - Using useRef in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM