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

时间:2020-02-10 02:19:46

标签: arrays reactjs react-native object react-hooks

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

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个对象对。

1 个答案:

答案 0 :(得分: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);
}

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