头图

The text starts here~

Overview

React's ref usually returns undefined or null when we try to access its current attribute before its corresponding DOM element is rendered. To solve this problem, you can access ---b84abd988d0cdcc13909c1fb805c490a--- in the useEffect hook, or access ref ref the event is triggered.

 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() hook can be passed an initial value as a parameter. The hook returns a mutable ref ref object with the current property on the ---f2dd22b763f159a12b20abcc728b8809--- object initialized to the passed parameter.

We didn't pass an initial value for useRef , so its current property was set to undefined . If we pass null to the hook, if we access its current property immediately, we will get null .

ref ,我们必须访问---81d833369b0372b691545eb6269256ad---对象上的current 84e31acbd7fc11f2f9e703b01d9a0223---属性,以此来ref div元素.

当我们为元素传递ref属性时,比如说, <div ref={myRef} /> ,React ref .current的DOM node.

We use the useEffect hook because we want to make sure that ref has been set on the element and that the element has been rendered to the DOM.

ref上的current ,我们会得到undefined,是ref还没有被设置, div element has not been rendered.

event

You can also access the ref current property of ---43f172e66ef1fac5acee35443ada33f0--- in the event handler.

 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>
  );
}

When the user clicks the button, ref has been set and the corresponding element has been rendered into the DOM, so we can access it.

Summarize

You can access ref ref the useEffect hook, or ---e824a6ed3caffa51eca3902492bc0268--- when the event is triggered. That is, to make sure the element has been rendered to the DOM.


chuck
303 声望41 粉丝