首页 > 解决方案 > userRef 或 createRef 在功能组件中返回未定义

问题描述

我在这里阅读了很多答案,但它们都是类组件的潮流。

如果我有使用 useRef 或 createRef 的简单功能组件,则 ref.current 未定义我将其分配在 div 或 input 之上,但我无法获得它们的任何属性

Console.log() 仅在我使用独立控制台时才给我数据 console.log(ref) 其他所有属性都未定义,例如 console.log(ref.current)

import React, { useRef } from "react";
import ReactDOM from "react-dom";

function App() {
  const ref = useRef()
  console.log(ref.current) // undefined
  console.log(ref) // { current }

  return ( 
    <div className="App">
      <h1 ref={ref}>Hello CodeSandbox</h1>      
      {/* <input ref={ref} name="test" value="bla" /> */}
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

查看此演示并查看控制台: https ://codesandbox.io/s/fervent-kirch-soe8n

但即使在类组件中,我也无法访问例如 ref.current.innerHTML: https ://codesandbox.io/s/relaxed-beaver-ic1em

标签: reactjs

解决方案


您将 ref 提供给 dom 中的元素,因此在实际渲染之前您无法访问它,因此在组件生命周期中发生的反应,即 useEffect 或 componentDidMount。

import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const ref = useRef();
 useEffect(() => {
   console.log(ref.current)
 },[])

  return (
    <div className="App">
      <h1 ref={ref}>Hello CodeSandbox</h1>
      {/* <input ref={ref} name="test" value="bla" /> */}
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const Expander = forwardRef((_, ref) => {
  return <div ref={ref}>test</div>;
});

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


推荐阅读