Javascript 只有数字。在 React 中输入数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43687964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Only numbers. Input number in React
提问by lalala
I'm trying to exclude minus and plus from input, but it's going wrong:
我试图从输入中排除减号和加号,但它出错了:
handleChange(event) {
const value = event.target.value.replace(/\+|-/ig, '');
this.setState({financialGoal: value});
}
Render input code:
渲染输入代码:
<input style={{width: '150px'}} type="number" value={this.state.financialGoal} onChange={this.handleChange}/>
回答by Samuli Hakoniemi
I tried to mimic your code and noticed that there's an issue on Reactwith <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010
我试图模仿您的代码并注意到Reactwith <input type='number' />. 如需解决方法,请查看此示例并自行尝试:https: //codepen.io/zvona/pen/WjpKJX?editors=0010
You need to define it as normal input (type='text') with pattern for numbers only:
您需要将其定义为普通输入(type='text'),仅使用数字模式:
<input type="text" pattern="[0-9]*"
onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
And then to compare the validity of input:
然后比较输入的有效性:
const financialGoal = (evt.target.validity.valid) ?
evt.target.value : this.state.financialGoal;
The biggest caveat on this approach is when it comes to mobile --> where keyboard isn't in numeric but in normal alphabetic format.
这种方法的最大警告是当涉及到移动时 --> 键盘不是数字而是正常的字母格式。
回答by francojohnc
one line of code
一行代码
<input value={this.state.financialGoal} onChange={event => this.setState({financialGoal: event.target.value.replace(/\D/,'')})}/>
回答by Abdennour TOUMI
To stop typing, use
onKeyPressnotonChange.Using
event.preventDefault()insideonKeyPressmeans STOP the pressing event .Since
keyPresshandler is triggered beforeonChange, you have to check the pressed key (event.keyCode), NOT the current value of input (event.target.value)onKeyPress(event) { const keyCode = event.keyCode || event.which; const keyValue = String.fromCharCode(keyCode); if (/\+|-/.test(keyValue)) event.preventDefault(); }
要停止输入,请使用
onKeyPressnotonChange。使用
event.preventDefault()insideonKeyPress意味着停止按下事件。由于
keyPress之前触发处理程序onChange,您必须检查按下的键 (event.keyCode),而不是输入 (event.target.value)的当前值onKeyPress(event) { const keyCode = event.keyCode || event.which; const keyValue = String.fromCharCode(keyCode); if (/\+|-/.test(keyValue)) event.preventDefault(); }
Demo below
下面的演示
const {Component} = React;
class Input extends Component {
onKeyPress(event) {
const keyCode = event.keyCode || event.which;
const keyValue = String.fromCharCode(keyCode);
if (/\+|-/.test(keyValue))
event.preventDefault();
}
render() {
return (
<input style={{width: '150px'}} type="number" onKeyPress={this.onKeyPress.bind(this)} />
)
}
}
ReactDOM.render(<Input /> , document.querySelector('#app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section id="app"></section>
回答by Jimmay
If you want to maintain input type='number'(probably for mobile devices to trigger the numeric keyboard) you should use onInputinstead of onChangeto capture your event changes.
如果您想保持输入type='number'(可能用于移动设备触发数字键盘),您应该使用onInput而不是onChange捕获您的事件更改。
Using onInputfixed a bug where typing text into a number input would bypass the validation I had assigned to it in onChange. Once I fixed this function to be called in onInputit triggered in all instances.
使用onInput修复了一个错误,即在数字输入中输入文本会绕过我在onChange. 一旦我修复了要在onInput其中调用的此函数,它就会在所有情况下触发。
Here's an example of what I'm doing:
这是我正在做的一个例子:
<input
type='number'
id={`player${index}Score`}
className='form-control'
pattern='[0-9]{0,5}'
onInput={(event) => this.enterScore(event, index)}
value={this.props.scoreLabel(this.state.scores[index])}
/>
I hope this helps!
我希望这有帮助!
EDIT - 08-03-2018:
编辑 - 08-03-2018:
I came up with a better solution. Use type='tel' along with a pattern regex within the input component itself.
我想出了一个更好的解决方案。在输入组件本身中使用 type='tel' 和模式正则表达式。
The nuts and bolts of how I wired this up is here:
我如何连接它的螺母和螺栓在这里:
class Input extends React.Component {
state = {message: '3'};
updateNumber = (e) => {
const val = e.target.value;
// If the current value passes the validity test then apply that to state
if (e.target.validity.valid) this.setState({message: e.target.value});
// If the current val is just the negation sign, or it's been provided an empty string,
// then apply that value to state - we still have to validate this input before processing
// it to some other component or data structure, but it frees up our input the way a user
// would expect to interact with this component
else if (val === '' || val === '-') this.setState({message: val});
}
render() {
return (
<input
type='tel'
value={this.state.message}
onChange={this.updateNumber}
pattern="^-?[0-9]\d*\.?\d*$"
/>
);
}
}
ReactDOM.render(<Input />, document.getElementById('main'));
I have an example of this working on Codepen here
回答by Zhijian
Solution
解决方案
Today I find use parseInt()is also a good and clean practice. A onChange(e)example is below.
今天我发现使用parseInt()也是一个很好的和干净的做法。onChange(e)下面是一个例子。
Code
代码
onChange(e){
this.setState({[e.target.id]: parseInt(e.target.value) ? parseInt(e.target.value) : ''})
}
Explanation
解释
parseInt()would returnNaNif the parameter is not a number.parseInt('12a')would return 12.
parseInt()NaN如果参数不是数字,将返回。parseInt('12a')将返回 12。
回答by zishe
The most effective and simple solution I found:
我发现的最有效和最简单的解决方案:
<input
type="number"
name="phone"
placeholder="Phone number"
onKeyDown={e => /[\+\-\.\,]$/.test(e.key) && e.preventDefault()}
/>
回答by Skid Kadda
2019 Answer Late, but hope it helps somebody
2019 回答晚了,但希望它对某人有所帮助
This will make sure you won't get null on an empty textfield
这将确保您不会在空文本字段上获得 null
- Textfield value is always 0
- When backspacing, you will end with 0
- When value is 0 and you start typing, 0 will be replaced with the actual number
- 文本字段值始终为 0
- 退格时,您将以 0 结尾
- 当值为 0 并且您开始输入时,0 将替换为实际数字
// This will make sure that value never is null when textfield is empty
const minimum = 0;
export default (props) => {
const [count, changeCount] = useState(minimum);
function validate(count) {
return parseInt(count) | minimum
}
function handleChangeCount(count) {
changeCount(validate(count))
}
return (
<Form>
<FormGroup>
<TextInput
type="text"
value={validate(count)}
onChange={handleChangeCount}
/>
</FormGroup>
<ActionGroup>
<Button type="submit">submit form</Button>
</ActionGroup>
</Form>
);
};
回答by Foram Shah
Set class on your input field:
在输入字段上设置类:
$(".digitsOnly").on('keypress',function (event) {
var keynum
if(window.event) {// IE8 and earlier
keynum = event.keyCode;
} else if(event.which) { // IE9/Firefox/Chrome/Opera/Safari
keynum = event.which;
} else {
keynum = 0;
}
if(keynum === 8 || keynum === 0 || keynum === 9) {
return;
}
if(keynum < 46 || keynum > 57 || keynum === 47) {
event.preventDefault();
} // prevent all special characters except decimal point
}
Restrict paste and drag-drop on your input field:
限制在输入字段上粘贴和拖放:
$(".digitsOnly").on('paste drop',function (event) {
let temp=''
if(event.type==='drop') {
temp =$("#financialGoal").val()+event.originalEvent.dataTransfer.getData('text');
var regex = new RegExp(/(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/g); //Allows only digits to be drag and dropped
if (!regex.test(temp)) {
event.preventDefault();
return false;
}
} else if(event.type==='paste') {
temp=$("#financialGoal").val()+event.originalEvent.clipboardData.getData('Text')
var regex = new RegExp(/(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/g); //Allows only digits to be pasted
if (!regex.test(temp)) {
event.preventDefault();
return false;
}
}
}
Call these events in componentDidMount() to apply the class as soon as the page loads.
在页面加载后立即在 componentDidMount() 中调用这些事件以应用该类。
回答by Marquistador
Define an input with an onChange()method like below (in my case, childState contains the state, passed down to this child component).
使用如下onChange()方法定义输入(在我的情况下,childState 包含传递给此子组件的状态)。
<input
...
value={this.props.childState.volume}
...
onChange={(e) => handleChangeInteger(e, {volume: e.target.value})}
/>
One approach I used was to install validatorJS(npm install validator --save)
我使用的一种方法是安装validatorJS( npm install validator --save)
I then defined a function handleChangeInteger, which takes an object that will be used to change your state, in this case, {volume: e.target.value}. Note: I needed the OR condition to allow my input to be blank, otherwise it would not let the user backspace (delete) the last integer if they wanted the field blank.
然后我定义了一个 function handleChangeInteger,它接受一个将用于更改状态的对象,在本例中为{volume: e.target.value}. 注意:我需要 OR 条件来允许我的输入为空,否则如果用户想要该字段为空,它不会让用户退格(删除)最后一个整数。
const handleChangeInteger = (e, obj_to_return) => {
if (validator.isInt(e.target.value) || e.target.value == '') {
this.props.childSetState(obj_to_return)
}
}
The user will now not be allowed to type anything other than backspace, 0-9, or e (this is a number..) in the input field.
现在不允许用户在输入字段中键入除退格键、0-9 或 e(这是一个数字..)以外的任何内容。
I referenced this post to create my solution: https://stackoverflow.com/a/45676912/6169225
我参考了这篇文章来创建我的解决方案:https: //stackoverflow.com/a/45676912/6169225
回答by Stanislav Stadnyk
Maybe, it will be helpful for someone
Recently I used this solution for my App
I am not sure that is a correct solution but it works fine.
也许,这对某人会有所帮助
最近我将这个解决方案用于我的应用程序
我不确定这是一个正确的解决方案,但它工作正常。
this.state = {
inputValue: "",
isInputNotValid: false
}
handleInputValue = (evt) => {
this.validationField(evt, "isInputNotValid", "inputValue");
}
validationField = (evt, isFieldNotValid, fieldValue ) => {
if (evt.target.value && !isNaN(evt.target.value)) {
this.setState({
[isFieldNotValid]: false,
[fieldValue]: evt.target.value,
});
} else {
this.setState({
[isFieldNotValid]: true,
[fieldValue]: "",
});
}
}
<input className={this.state.isInputNotValid ? "error" : null} type="text" onChange="this.handleInputValue" />
The main idea, that state won't update till the condition isn't true and value will be empty.
Don't need to use onKeyPress, Down etc.,
also if you use these methods they aren't working on touch devices
主要思想是,在条件不为真且值为空之前,该状态不会更新。
不需要使用 onKeyPress、Down 等,
如果您使用这些方法,它们也不适用于触摸设备

