[英]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
所以,在
useEffect
或useLayoutEffect
中调用它
// run synchronously after all DOM mutations
React.useLayoutEffect(() => {
// do something with inputRef
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.