reactjs - 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
解决方案
您将 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);
推荐阅读
- angular - 检查登录方法的承诺不会将承诺返回给 canActivate()
- sharepoint - azure adal 无法在 sharepoint 文档库中上传文件
- javascript - 为什么不通过 jquery 将布尔值分配给下拉列表?
- python - django:当 2 个字段具有相同值时过滤查询集
- angular - 我如何在打字稿中为 Angular 5 设置 zindex
- angular - 我什么时候应该在 Angular 2+ 中使用 TS 导入类型?
- amazon-web-services - 基于 S3 触发器更新 S3 上的文件
- sql-server - 使用 SQL 参数返回“参数类型错误”
- java - Antlr3 SQL语法中无法提供宿主变量
- windows - 使用 ExtendedSubCommandsKey(和 python _winreg)的 Windows 级联上下文菜单