【问题标题】:React > How to set focus on the input field after adding a new row by using react-tableReact > 如何在使用 react-table 添加新行后将焦点设置在输入字段上
【发布时间】:2020-06-03 04:08:30
【问题描述】:
【问题讨论】:
标签:
reactjs
react-table
react-ref
【解决方案1】:
我使用普通的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);
};
我使用requestAnimationFrame 是因为我在操作 DOM,查看此answer 了解更多详情。
【解决方案2】:
您正在尝试在功能组件上应用 forwardRef() 并且 React 文档说
你不能在函数组件上使用 ref 属性React ref doc
您可以使用useImeprativeHandle() 可以;
const Table = React.forwardRef((props, ref) => {
const inputRef = React.useRef();
React.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}), []);
return <Editable ref={inputRef} {...props} />;
}
现在您可以通过创建 ref 并调用命令式方法来访问 ref。我没有研究如何聚焦您的元素,但您可以使用命令式句柄来处理 forwardRef 问题。
或
您可以将 EditTable 组件转换为基于分类的组件。