表单字段在输入时失去输入焦点

时间:2016-10-05 09:55:21

标签: reactjs underscore.js

我正在努力实施以下double,用户可以输入:Account Details& Account Currency

以下列格式从服务器检索数据:

{
  ...,
  "invoiceConfiguration": {
    "id": 290271069734815,
    "bankConfigs": [
      {
        "bankDetails": "Bank Details Euro",
        "currency": {
          "id": 17592186045607,
          "name": "Euro",
          "iso": "EUR"
        }
      },
      {
        "bankDetails": "USD Test Bank details",
        "currency": {
          "id": 17592186045610,
          "name": "US Dollar",
          "iso": "USD"
        }
      }
    ]},
    ...
}

我在render()函数中实现了以下内容。

银行账户
    {_.map(this.state.company.invoiceConfiguration.bankConfigs, (bankConfig, i) => {
      return (
        <div className="row" key={_.uniqueId("bankDetailRow_")}>
          <div className="small-12 medium-6 columns">
            <label>
              Account Details
              <textarea rows="6" value={bankConfig.bankDetails} onChange={event => this.onBankDetailsChange("bankDetails", i, event.target.value)} />
            </label>
          </div>
          <div className="small-12 medium-4 columns">
            <label>
              Currency
              <Select
                name="bankCurrency"
                placeholder="Bank Account Currency"
                value={bankConfig.currency.id}
                options={currencyTypeOptions}
                onChange={_.partial(this.onBankDetailsChange, "currency", i)} />
            </label>
          </div>
        </div>
      )
    })}

onBankDetailsChange()函数定义如下:

onBankDetailsChange(key, pos, val) {
    if (key === "currency") {
      val = {
        id: val.value
      };
    }
    const company = this.state.company;
    let bankAccounts = company.invoiceConfiguration.bankConfigs;
    bankAccounts[pos][key] = val;
    company.invoiceConfiguration.bankConfigs = bankAccounts;
    this.setState({
      company,
      status: "unsaved"
    });
  }

每次输入内容时,输入字段都会失去焦点。

1 个答案:

答案 0 :(得分:0)

从这里回答:http://reactkungfu.com/2015/09/react-js-loses-input-focus-on-typing/

在我们的例子中,有问题的代码在这里:

<div className="row" key={_.uniqueId("bankDetailRow_")}>

由于key是唯一的,因此每次状态它抛弃旧的div并在其位置添加新的div。它看起来很相似,但它失去了重点。

解决方案是使用不会发生变化的key。在这里,这有效:

<div className="row" key={i}>