我有一个有条件渲染的组件,我通过React的forwardRef将引用传递给它,但是当条件满足并且组件渲染时,引用仍然没有任何值, 我该怎么办?
这是我的模拟代码
import { useEffect, useState, useRef } from "react";
import "./styles.css";
import Table from "./Table";
export default function App() {
const [list, setList] = useState([]);
const ref = useRef(null);
useEffect(() => {
setTimeout(() => {
setList(["faraz"]);
}, 1000);
}, []);
console.log("ref************", ref);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{!!list.length && <Table ref={ref} />}
</div>
);
}
还有我的孩子和条件渲染组件
import React from "react";
const Table = React.forwardRef((props, ref) => {
return (
<div>
<p>test</p>
<div ref={ref}></div>
</div>
);
});
export default Table;
我尝试将 ref 和前向 ref 传递给子组件,但 ref 从未获取值,如何在条件渲染组件上设置 ref 值
在您的示例中
ref
实际上确实有一个值,只是没有被记录。
要了解原因,让我们逐步分析您提供的代码中发生的情况:
list = []; ref.current = null
console.log("ref************", ref); // logs: '{current: null}'
list.length === 0
,Table 不会渲染,所以 ref.current
保持为 nulluseEffect
运行,触发状态更新list = ["faraz"]; ref.current = null
console.log("ref************", ref); // logs: '{current: null}'
list.length === 1
,表格也会渲染并设置 ref.current = {current: HTMLDivElement {...}}
console.log
没有机会记录新的ref.current
值。要验证您的
ref.current
值是否实际设置,您可以更新代码以渲染 Table,无论 list
长度如何,这都会在 first渲染上设置
ref.current
,从而导致在第二次渲染期间出现 console.log
记录其值。
您可以在此处找到具有描述的更新的代码https://playcode.io/1863189