如何等待 ref 准备好,但又只能在有条件的使用效果内工作?
这是我想做的:
当弹出窗口可见时,我想使用 ref 选择 DataGrid 组件中的所有行。
这段代码不起作用,因为我当时没有引用当前实例。
useEffect(() => {
if (isVisible) {
dataGridRef.current.instance.selectAll()
}
}, [isVisible])
所以我搜索并发现 useCallback 在 ref 连接时更新。
const dataGridRef = useCallback(node => {
if (node !== null) {
node.instance.selectAll()
}
}, [])
<DataGrid ref={dataGridRef} ..
但是这一次,当我必须重置时我无法使用 ref 实例(使用 ref 取消选择数据网格)
最佳答案
您的回调引用将捕获对节点进行更改的时间,并且在同一函数执行中,您可以随心所欲地更新要在回调外部引用的引用对象。
// define a ref object and a ref function
const dataGridRef = useRef(null);
const dataGridFuncRef = useCallback(node => {
// manually update the ref object each time the dom element changes
dataGridRef.current = node.instance;
node.instance?.selectAll();
}, []);
const deselectOnClick = (event) => {
// now we can use the ref instance outside the callback
dataGridRef.current?.instance?.deselectAll();
}
// ... inside the render function ...
<DataGrid ref={dataGridFuncRef} />
这是一个example CodeSandbox上述概念。
关于reactjs - useRef 和 useEffect 初始访问,然后使用 useRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71945693/