如何等待 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} />
这里是上述概念的 CodeSandbox 示例。
你可以尝试做类似的事情
useEffect(() => {
if (isVisible && dataGridRef?.current) {
dataGridRef.current.instance.selectAll()
}
}, [isVisible])
此外,您可以链接
?
运算符来检查 null