【问题标题】: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
【问题描述】:

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

只有一件事有更好的用户界面,我想在点击添加新按钮后专注于新项目的输入字段。

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

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

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

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

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

答案here

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

【问题讨论】:

    标签: 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 组件转换为基于分类的组件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-28
        • 1970-01-01
        • 2021-03-18
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 2018-04-16
        相关资源
        最近更新 更多