美好的一天,
我有
CellItem
组件失去了某些的焦点,但不是全部。它使用 Material UI 的 TextField
组件。
package.json
"@emotion/styled": "^11.13.0",
"@mui/icons-material": "^5.16.7",
"@mui/material": "^5.16.7",
CellItem.js
function CellItem(props) {
const {
id,
name,
initialValue,
onUpdateVolumeItem,
maxWidth
} = props;
const [value, setValue] = useState(initialValue);
const onValueChange = (e) => {
e.stopPropagation();
e.preventDefault();
let inputValue = e.target.value;
onUpdateVolumeItem(inputValue, id, name);
}
return (
<TableCell
id={id}
scope="row"
padding="none"
sx={{ m: 1, maxWidth }}
onClick={(e) => e.stopPropagation()}
>
<TextField
fullWidth
value={value}
onChange={e => onValueChange(e)}
/>
</TableCell>
);
}
CellItem.defaultProps = {
maxWidth: 110
}
export default React.memo(CellItem);
例如,这是包含两个单元格的行。
function VolumeItem(props) {
//....
return (
<TableRow
hover
role="checkbox"
tabIndex={-1}
key={item._id}
sx={{ cursor: 'pointer', backgroundColor: item.isAdded ? "#FFFFE0": "white"}}
>
<CellItem
id={item._id}
name="project"
initialValue={item.project}
onUpdateVolumeItem={onUpdateVolumeItem}
/>
<CellItem
id={item._id}
name="quarter"
initialValue={item.quarter}
onUpdateVolumeItem={onUpdateVolumeItem}
/>
</TableRow>
);
}
export default React.memo(VolumeItem);
奇怪的是,按一下键后,
"project"
文本字段就会失去焦点。但是,多次按键后 "quarter"
文本字段不会失去焦点。
在我的实际项目中,14 个文本字段中有 3 个存在此问题。
我尝试使用
keys
在非动态文本字段中添加 item._id
,但并不适用于所有人。
还有其他想法或想法为什么会发生这种情况吗?
非常感谢!
上面的代码有几个问题。
VolumeItem
中,您有两个 CellItem
的 id
属性具有相同的值。尝试删除这些道具或使用唯一的 ID。TextField
正在使用受控的value
,但setValue
从未被调用。onValueChange
中,e.stopPropagation()
和 e.preventDefault()
不是必需的。