首頁  >  問答  >  主體

在反應中使用 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 天前373

全部回覆(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
  • 取消回覆