总览
当我们试图在其对应的DOM元素被渲染之前访问其 current 属性时,React的ref通常会返回 undefined 或者 null 。为了解决该问题,可以在 useEffect 钩子中访问 ref ,或者当事件触发时再访问 ref 。
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.current); // ??? undefined here useEffect(() => { const el2 = ref.current; console.log(el2); // ??? element here }, []); return ( <div> <div ref={ref}> <h2>Hello</h2> </div> </div> ); }
useEffect
useRef() 钩子可以传递一个初始值作为参数。该钩子返回一个可变的 ref 对象, ref 对象上的 current 属性被初始化为传递的参数。
我们没有为 useRef 传递初始值,因此其 current 属性设置为 undefined 。如果我们将 null 传递给钩子,如果立即访问其 current 属性,将会得到 null 。
需要注意的是,我们必须访问 ref 对象上的 current 属性,以此来访问设置了 ref 属性的 div 元素。
当我们为元素传递 ref 属性时,比如说, <div ref={myRef} /> ,React将 ref 对象的 .current 属性设置为相应的DOM节点。
我们使用 useEffect 钩子,是因为我们想要确保 ref 已经设置在元素上,并且元素已经渲染到DOM上。
如果我们尝试在组件中直接访问 ref 上的 current 属性,我们会得到undefined,是因为 ref 还没有被设置,而且 div 元素还没有被渲染。
事件
你也可以在事件处理函数中访问 ref 的 current 属性。
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.current); // ??? undefined here useEffect(() => { const el2 = ref.current; console.log(el2); // ??? element here }, []); const handleClick = () => { console.log(ref.current); // ??? element here }; return ( <div> <div ref={ref}> <h2>Hello</h2> </div> <button onClick={handleClick}>Click</button> </div> ); }
当用户点击按钮的时候, ref 已经被设置好了,相应的元素已经被渲染到DOM中,所以我们能够访问它。
总结
可以在 useEffect 钩子中访问 ref ,或者当事件触发时再访问 ref 。也就是说,要确保元素已经渲染到DOM上。
到此这篇关于React报错解决之ref返回undefined或null的文章就介绍到这了,更多相关React ref返回undefined null内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
附:ref的值根据节点的类型而有所不同
当在refHTML元素上使用该属性时,ref在构造函数中创建的属性将React.createRef()接收底层DOM元素作为其current属性。 在ref自定义类组件上使用该属性时,该ref对象将接收组件的已安装实例作为其current。您可能无法ref在函数组件上使用该属性,因为它们没有实例。
class CustomTextInput extends React.Component { constructor(props) { super(props); // create a ref to store the textInput DOM element this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this); } focusTextInput() { // Explicitly focus the text input using the raw DOM API // Note: we're accessing "current" to get the DOM node this.textInput.current.focus(); } render() { // tell React that we want to associate the <input> ref // with the `textInput` that we created in the constructor return ( <div> <input type="text" ref={this.textInput} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
current当组件安装时,React将为该属性分配DOM元素,并null在卸载时将其分配回。ref更新发生之前componentDidMount或componentDidUpdate生命周期方法。
原文链接: bobbyhadz.com/blog/react-…
作者: Borislav Hadzhiev
查看更多关于React报错解决之ref返回undefined或null的详细内容...