简体   繁体   English

无法在React中获取我的表单以正常工作

[英]Can't get my form in React to work properly

I'm creating a form where I want to add form rows and edit any row/cell at any time. 我正在创建一个表单,我想随时添加表单行并编辑任何行/单元格。 It seems to work fine by adding new rows but if I edit a previous row/cell the form fields get's messed up. 通过添加新行,它似乎可以正常工作,但是如果我编辑上一行/单元格,则表单字段会混乱。

This is my handleChange for each field: 这是我对每个字段的handleChange:

handleChange = (key, e) => {
  const { name, value } = e.target
  const currentRow = this.state.formRows.filter(r => r.key === key)[0]
  const withoutCurrentRow = this.state.formRows.filter(r => r.key !== key)
  const updatedRow = { ...currentRow, [name]: value }
  const newRows = [...withoutCurrentRow, updatedRow]
  this.setState(({ formRows }) => ({ formRows: newRows }))
}

Here's my form on codesandbox 这是我在codesandbox上的表格

You are passing in the arguments in wrong order for one of your inputs. 您为其中一个输入的参数传递顺序错误。 It should be the key as first argument and the event as second. 它应该是第一个参数是key ,第二个是event

<Input
  value={description}
  name="description"
  placeholder="description"
  style={{ width: '20%', marginRight: 8 }}
  onChange={e => this.handleChange(key, e)}
/>
<Input
  value={amount}
  name="amount"
  placeholder="amount"
  style={{ width: '20%', marginRight: 8 }}
  onChange={e => this.handleChange(key, e)}
/>

You could also use findIndex to get the index of the object you want to update, and create a new copy of that object in the array with an updated field. 您还可以使用findIndex来获取要更新的对象的索引,并使用更新的字段在数组中创建该对象的新副本。

handleChange = (key, e) => {
  const { name, value } = e.target;
  this.setState(previousState => {
    const formRows = [...previousState.formRows];
    const currentIndex = formRows.findIndex(row => row.key === key);

    formRows[currentIndex] = { ...formRows[currentIndex], [name]: value };

    return { formRows };
  });
};

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

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