这是我的代码,我在其中获取对我想要聚焦的当前元素的引用,但焦点不会转到该元素。
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>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您的
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]);