简体   繁体   English

如何在 React 中使用带有钩子的 onChange 更新数组元素?

[英]How do I update elements of array using onChange with hooks in React?

I believe this should be something simple but I find it difficult to implement, and all the answers I've seen so far doesn't really tackle this specific problem.我相信这应该很简单,但我发现很难实现,而且到目前为止我看到的所有答案并没有真正解决这个具体问题。 I have a state like this.我有一个像这样的 state。

const [formFields, setFormFields ] = useState({
formTitle: '',
field: [
    {name: '', options: ['optionA', 'optionB', 'OptionC'] },
]})

I want to update the elements of the options array using onChangeText/onChange.我想使用 onChangeText/onChange 更新options数组的元素。

My code我的代码

field.options.map((option) => (
<TextInput value={option} 
onChangeText={(e) => e}
/>))

Please how can I achieve this?请问我怎样才能做到这一点?

You can do that like this你可以这样做

const [formFields, setFormFields] = useState({
  formTitle: "",
  field: [{ name: "", options: ["optionA", "optionB", "OptionC"] }],
});

const onChangeHandler = (e) => {
  setFormFields({
    ...formFields,
    field: formFields.field.map((field) => ({ ...filed, options: /*your change */ })),
  });
};

Or use library like Immer .或者使用像Immer这样的库。 And then you just modify specific filed.然后你只需修改特定的文件。

const onChangeHandler = (e) => {
  setFormFields(
    produce(formFields, (draft) => {
      draft.field[0].options = /*your change */;

      // Or all the fields
      draft.field.forEach((field) => {
        field.options = /*your change */;
      });
    })
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM