reactjs - useRef 和 useEffect 初始访问,然后使用 useRef

标签 reactjs use-effect use-ref usecallback react-usecallback

如何等待 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/

相关文章:

javascript - 当通过 props 传入时,为什么需要 state 变量的 setter 作为 useEffect 的依赖项?

javascript - 将状态作为 Prop 传递给 child 是好的做法吗?

Javascript 推送本地存储项

reactjs - 阅读布局时, `useLayoutEffect` 比 `useEffect` 更可取吗?

reactjs - ESLint 详尽-deps : ignore value that came from a ref

javascript - 徽章内的全宽 material-ui 按钮?

reactjs - 为什么当底层组件重新渲染时,popper 会跳转到左上角?

reactjs - ESLint 警告 React 查询突变必须包含在依赖项数组中

javascript - react : Setinterval is not stopping even after clearing the timer using clearInterval

reactjs - React - 使用对象或数组在一行中创建多个 useRef