React Native-具有对象数组的动态表单和更新状态

问题描述 投票:0回答:1

如何动态显示多个输入字段并根据索引更新输入字段的状态。

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对,具体取决于数据,如何动态更新最终将具有的值:

[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
1个回答
0
投票

刚想出来...

const handleValue1 = (index, value) => {
  state[index] = {...state[index], ['value1']: value};
  /*setState(prevObj => ({
    ...prevObj[index],
    value1: value,
  }));*/
  console.log(state);
}

const handleValue2 = (index, value) => {
  state[index] = {...state[index], ['value1']: value};
  /*setState(prevObj => ({
    ...prevObj[index],
    value2: value,
  }));*/
  console.log(state);
}

对于其他可能感兴趣的人。

© www.soinside.com 2019 - 2024. All rights reserved.