首页 > 解决方案 > React > 如何在使用 react-table 添加新行后将焦点设置在输入字段上

问题描述

我决定用它react-table来构建网格。

拥有更好的 UI 只是一件事,那就是我想在单击添加新按钮后专注于新项目的输入字段。

我打算使用ref但不知道如何fowardRef使用子项

这是我使用 react-table 的示例:

https://codesandbox.io/s/beautiful-proskuriakova-lpfxn

在这种情况下,我想First Name在添加新行后专注于该字段。

在此处输入图像描述

更新: 我可以通过使用autoFocus原生 HTML 的支持来专注于输入。

答案在这里

但我仍然想通过使用来处理焦点React Ref

标签: reactjsreact-tablereact-ref

解决方案


我用plainJavaScript来实现你的目标

  const setFocus = () => {
    //Add id to the table
    document.getElementsByTagName("TABLE")[0].setAttribute("id", "mytable");

    //table > tbody > tr (latest added row) > td (first cell in the row) > input
    let cell = document.getElementById("mytable").lastElementChild
      .lastElementChild.firstElementChild.children[0];

    cell.focus();
  };

  const addNew = () => {
    setData(old => [...old, {}]);
    window.requestAnimationFrame(setFocus);
  };

使用 react-table 编辑可编辑

我使用requestAnimationFrame是因为我正在操作 DOM,请查看此答案以获取更多详细信息。


推荐阅读