简体   繁体   中英

Why React ref element.current returns null in React component using useRef hook?

I need to query a DOM element and using useRef hook:

const Overlay = ({ children }: Props) => {
  const myRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    console.log(myRef.current);
  }, [myRef]);


  return (
    <React.Fragment>
      <Dialog fullScreen open={open}>
        <DialogContent id="dialog" ref={myRef}>
          <header>
           // Header
          </header>
          {children}
        </DialogContent>
      </Dialog>
    </React.Fragment>
  );
};

export default Overlay;

If I inspect the console it returns null .

What do I have to do to query the DOM element using useRef ?

So the MUIs Dialog component only mounts it's children if open === true . I would suggest making your useEffect dependant on the open state instead of reference.

  useEffect(() => {
    if (open) {
      console.log(myRef.current);
    } else {
      // myRef.current is null
    }
  }, [open]);

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