reactjs - React > 如何在使用 react-table 添加新行后将焦点设置在输入字段上
问题描述
我决定用它react-table
来构建网格。
拥有更好的 UI 只是一件事,那就是我想在单击添加新按钮后专注于新项目的输入字段。
我打算使用ref
但不知道如何fowardRef
使用子项
这是我使用 react-table 的示例:
https://codesandbox.io/s/beautiful-proskuriakova-lpfxn
在这种情况下,我想First Name
在添加新行后专注于该字段。
更新:
我可以通过使用autoFocus
原生 HTML 的支持来专注于输入。
答案在这里
但我仍然想通过使用来处理焦点React 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);
};
我使用requestAnimationFrame
是因为我正在操作 DOM,请查看此答案以获取更多详细信息。
推荐阅读
- swift - 为什么这个功能在我添加命中框后立即停止工作?
- javascript - 使用复选框 JavaScript 进行多条件过滤
- python - 错误 - 使用 BeautifulSoup4 解析网页时
- loops - Racket expt 是否使用尾递归?
- javascript - 如何在IE11中获取地图的第一个键和值
- eclipse - Eclipse 插件开发:存储为 UTF8 的德语变音符号在 SWT 控件中显示错误,但在字符串常量中正确
- javascript - 如何从 Json 访问特定字段
- c - 我需要有人为我解释二叉树
- drupal - FeatureContext 文件中未定义步骤。我已经定义了步骤。不确定是否正在调用 featurecontext 文件
- javascript - Typescript React 只接受一个 html 子元素