我有一个受控的 Material-UI TextField 组件,它从父组件的状态中获取其值。在 TextField 失去焦点的情况下,我无法获得要更新的值。任何帮助将不胜感激
export function OtherApp() {
const [stateArray, setStateArray] = useState([{name: 'first', value: 'val'}, {name: 'second', value: 'val'}])
const changeHandler = (e, i) => {
let state = stateArray;
state[i].name = e.target.value;
setStateArray(state);
console.dir(state);
}
return (
<div>
{stateArray.map((el, i) => {
return (
<TextField
fullWidth
id={`section-${i}-namet`}
key={`section-${i}-namet`}
value={stateArray[i].name}
helperText='Helper Text'
onChange={e => changeHandler(e, i)}
/>
)
})}
</div>
)
}
答案 0 :(得分:0)
在更新之前克隆状态始终是最佳实践。尝试在您的 changeHandler 函数中添加以下代码
const changeHandler = (e, i) => {
let state = [...stateArray];
...
}