反应组件和无效输入 [英] React Component and Invalid Input
问题描述
我有以下反应组件:
var App = React.createClass({
getInitialState: function() {
return {value: 4.5}
},
change: function(event) {
this.setState({value: parseFloat(event.target.value)});
},
render: function() {
return <input type="number" value={this.state.value} onChange={this.change}/>;
}
});
React.render(<App/>, document.body);
你可以在这里看到: http://jsfiddle.net/2hauj2qg/
问题在于,如果我想输入如下数字: 4.7。当用户输入4时,由于被转换为后面的浮动,它变为4。但这会中断用户输入的内容。解决这个问题的推荐方法是什么?
The problem is that if I want to type in a number like: "4.7". When the user enters, "4.", it becomes "4", due to being converted to a float in back. But this interrupts what the user was typing. What's the recommended way of solving this problem?
推荐答案
正如我所提到的,这是因为你正在使用parseFloat
As imjared mentioned, it's because you're using parseFloat
this.setState({value: parseFloat(event.target.value)});
相反,您可能希望只允许数字和小数。它保持存储为字符串并且永远不会改变它们的输入,但是它们不能输入字母和空格之类的东西。
Instead, you may wish to only allow digits and the decimal. It stays stored as a string and never changes their input, but they're prevented from typing things like letters and spaces.
var nonNumericRegex = /[^0-9.]+/g;
this.setState({value: event.target.value.replace(nonNumericRegex, "")});
要允许负数,您需要这样做:
To allow negative numbers you need to do this:
this.setState({
value: event.target.value
.replace(nonNumericRegex, "")
.replace(/^(-.*?)-/g, "$1")
});
强制执行一个领先的美元符号并且不超过两位小数,如果是第一个字符(在$)是小数,前缀为0。
To enforce a leading dollar sign and no more than two decimals, and if the first character (after the $) is the decimal, prefix it with 0.
this.setState({
value: "$" + event.target.value
.replace(nonNumericRegex, "")
.replace(/(\.\d\d)\d+/g, "$1")
.replace(/^\./g, "0.")
})
这篇关于反应组件和无效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!