首页 > 解决方案 > 如何避免在反应中保存错误的输入数据?

问题描述

出于百分比目的,我有许多相同的输入,如果我使用普通数字数据,它们中的每一个都可以正常工作。如果我输入了错误的错误数据,如字母或其他字符,则将其更改为0. 但它只是在屏幕上发生变化,数据实际上是错误的。例如,如果我将在屏幕中输入结果,0fsdfsd但输入中的实际数据将是. 如何将实际数据保存为但不保存为?input00f00f

intl用来将数据格式化为十进制,并isNaN捕获 NaN 值。

render() 中的输入

<input
  name="bonusCategory"
  value={this.toCurrency(category.bonusrate)}
  className="form-control"
  style={{ width: "60px" }}
  type="text"
  onChange={this.inputChanged.bind(this, idx, category.value)}
/>
/>

toCurrency()

toCurrency(number) {
  const formatter = new Intl.NumberFormat("ru-RU", {
    style: "decimal"
  });
  let newValue = isNaN(number) ? 0 : number;
  return formatter.format(newValue);
}

输入改变()

inputChanged = (idx, index, e) => {
  const { categories } = this.state;
  let bonusCategory = e.target.value;
  console.log(bonusCategory);
  if (bonusCategory.length > 3) return;
  categories.forEach(category => {
    category.bonusrate =
      category.value === index ? e.target.value : category.bonusrate;
  });
  this.setState(oldState => {
    const newDisabledButtons = [...oldState.disabledButtons];
    newDisabledButtons[idx] = false;
    return {
      categories,
      isEdit: false,
      inCart: true,
      disabledButtons: newDisabledButtons
    };
  });
};

console.log我可以看到不断变化的数据,bonusCategory它显示错误的结果。笔:https ://codepen.io/fatdrfrog/pen/rNBXwrW

标签: javascriptreactjs

解决方案


如果你想使用一些不event用于 onChange 处理程序的参数,请试试这个。


    inputChanged = (idx, categoryvalue) => (e) => {
    ... ... ...
    };


推荐阅读