首页  >  问答  >  正文

在反应中使用 useRef 钩子后焦点不会移动

这是我的代码,我在其中获取对我想要聚焦的当前元素的引用,但焦点不会转到该元素。

  useEffect(() => {
    setTimeout(() => { 
      console.log("This is current barcode ref inside", barcodeRef.current);
      barcodeRef.current && barcodeRef.current.focus(); 
    }, 500)
    //barcodeRef.current && barcodeRef.current.focus();
  }, [tableData]);

这也是我引用我想要关注的输入元素的方式。

            {tableData.map((row, rowIndex) => (
              <TableRow key={rowIndex}>
                {columns.map(
                  (column) =>
                    !column.hidden && (
                      <TableCell
                        key={column.accessorKey}
                        style={{ width: column.width }}
                      >
                        {column.accessorKey === "ItemName" ? (
                          <Input
                            value={row[column.accessorKey] || ""}
                            onChange={(event) =>
                              handleLeaveItem(
                                rowIndex,
                                column.accessorKey,
                                event.target.value
                              )
                            }
                          />
                        ) : (
                          <Input
                            ref={column.accessorKey === "Barcode" ? barcodeRef : null}//reference to the input of barcode column in table row
                            value={row[column.accessorKey] || ""}
                            onChange={(event) =>
                              handleSaveCell(
                                rowIndex,
                                column.accessorKey,
                                event.target.value
                              )
                            }
                          />
                        )}
                      </TableCell>
                    )
                )}
                <TableCell>
                    <IconButton onClick={() => handleRemoveRow(rowIndex)}>
                      <Delete />
                    </IconButton>
                  </TableCell>
              </TableRow>
            ))}

我也尝试过使用useLayoutEffect,但没有成功。在控制台中,我得到的是我想要关注的正确输入元素。

<div class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-colorPrimary css-10tgus4-MuiInputBase-root-MuiInput-root">
::before
<input type="text" class="MuiInputBase-input MuiInput-input css-ume8vi-MuiInputBase-input-MuiInput-input" value>
::after
</div>

P粉358281574P粉358281574171 天前375

全部回复(1)我来回复

  • P粉828463673

    P粉8284636732024-04-03 19:38:35

    您的 useEffect 需要依赖于 barcodeRef,如下所示:

    useEffect(() => {
        const timeout = setTimeout(() => { 
          console.log("This is current barcode ref inside", barcodeRef.current);
          barcodeRef.current && barcodeRef.current.focus(); 
        }, 500)
    
        return () => clearTimeout(timeout);
    }, [tableData, barcodeRef]);
    

    回复
    0
  • 取消回复