gpt4 book ai didi

reactjs - React > 如何在使用 react-table 添加新行后将焦点设置在输入字段上

转载 作者:行者123 更新时间:2023-12-04 13:16:10 27 4
gpt4 key购买 nike

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

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

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

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

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

在这种情况下,我想在添加新行后关注字段 First Name

enter image description here

更新:通过使用原生 HTML 的 autoFocus 支持,我能够专注于输入。

答案here

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

最佳答案

我使用纯 JavaScript 来实现您的目标

  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);
};

Edit Editable with react-table

我使用了 requestAnimationFrame 因为我正在操纵 DOM,请查看此 answer了解更多详情。

关于reactjs - React > 如何在使用 react-table 添加新行后将焦点设置在输入字段上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com