【发布时间】:2020-05-25 08:28:14
【问题描述】:
如何处理动态显示的多个输入字段并根据索引更新输入字段状态。
const [state, setState] = useState[{value1: '', value2: ''}]
const handleValue1 = (index, value) => {
setState(prevObj => ({
...prevObj[index],
value1: value,
}));
console.log(state);
}
const handleValue2 = (index, value) => {
setState(prevObj => ({
...prevObj[index],
value2: value,
}));
console.log(state);
}
return (
<FlatList
data={DATA}
renderItem={({item, index}) => (
<TextInput
onChangeText={e => handleValue1(index, e)}
value={state.value1}
/>
<TextInput
onChangeText={e => handleValue2(index, e)}
value={state.value2}
/>
/>
)
可能有多个 TextInput 对,具体取决于 DATA,我如何动态更新最终我将拥有的值:
[0]: {
value1: 'some value',
value2: 'another value',
},
[1]: {
value1: 'some value from another update',
value2: 'another value from another update again',
}
问题是,如果我更新 1 个 TextInput,所有 TextInput 字段都将更新为相同的数字,然后更新的状态会擦除数组,只保留 1 个对象对。
【问题讨论】:
标签: arrays reactjs react-native object react-hooks