簡體   English   中英

無法在React中獲取我的表單以正常工作

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

我正在創建一個表單,我想隨時添加表單行並編輯任何行/單元格。 通過添加新行,它似乎可以正常工作,但是如果我編輯上一行/單元格,則表單字段會混亂。

這是我對每個字段的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 }))
}

這是我在codesandbox上的表格

您為其中一個輸入的參數傳遞順序錯誤。 它應該是第一個參數是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)}
/>

您還可以使用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