javascript - 如何避免在反应中保存错误的输入数据?
问题描述
出于百分比目的,我有许多相同的输入,如果我使用普通数字数据,它们中的每一个都可以正常工作。如果我输入了错误的错误数据,如字母或其他字符,则将其更改为0
. 但它只是在屏幕上发生变化,数据实际上是错误的。例如,如果我将在屏幕中输入结果,0fsdfsd
但输入中的实际数据将是. 如何将实际数据保存为但不保存为?input
0
0f
0
0f
我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
解决方案
如果你想使用一些不event
用于 onChange 处理程序的参数,请试试这个。
inputChanged = (idx, categoryvalue) => (e) => {
... ... ...
};
推荐阅读
- java - 如何验证正文中每个数组项中的值或另一个值?
- powershell - 避免模块中的变量被调用者覆盖,反之亦然
- python - 如何根据日期列更改线图的颜色?
- meteor - 需要帮助:“构建不是流星命令”?
- c++ - C ++多线程给出不同的结果
- docker - 如何从外部机器向 docker-compose 内的 docker 映像(grpc 服务器)发送请求?
- laravel - 在 url 参数绑定旁边设置 laravel 中路由的默认值
- python - django request.session.clear() 和request.session.flush() 的区别?
- google-cloud-platform - 什么 gcloud 命令会列出具有特定网络标签的所有资源?
- security - 使用 gitlfs 存储库的包含模式给出:批处理响应:找不到存储库或对象: