Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 为什么React ref element.current使用useRef钩子在React组件中返回null?_Reactjs_Ref_Use Ref - Fatal编程技术网

Reactjs 为什么React ref element.current使用useRef钩子在React组件中返回null?

Reactjs 为什么React ref element.current使用useRef钩子在React组件中返回null?,reactjs,ref,use-ref,Reactjs,Ref,Use Ref,我需要查询DOM元素并使用useRefhook: const Overlay = ({ children }: Props) => { const myRef = useRef<HTMLDivElement>(null); useEffect(() => { console.log(myRef.current); }, [myRef]); return ( <React.Fragment> <Dialog

我需要查询DOM元素并使用
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;
const Overlay=({children}:Props)=>{
const myRef=useRef(null);
useffect(()=>{
console.log(myRef.current);
},[myRef]);
返回(
//标题
{儿童}
);
};
导出默认覆盖;
如果我检查控制台,它将返回
null


如何使用
useRef
查询DOM元素?

因此,如果
open==true
,MUIs
对话框
组件只装载它的子元素。我建议让您的
useffect
依赖于
open
状态,而不是参考

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

@谢谢你。但是在我的情况下,我必须如何使用
React.forwardRef
(使用Material UI对话框或DialogContent?我希望
MaterialUI
将ref转发给底层的本机DOM元素。检查他们的文档,看看他们是否允许用户访问底层的DOM元素。@如果你的意思是不使用
forwardRef
?只需像我的示例中那样使用
ref
属性即可?根据他
ref
被转发到根元素。但问题是,为什么它现在返回
null
?@Yousaf刚刚发现。我不得不将prop
disablePortal
添加到材质UI
。现在它开始工作了!