在React(antd样式)的Input中仅允许数字 [英] Allow only numbers in Input in React (antd styling)
问题描述
我知道type = number可以用,但这不是我想要的.我的HTML:
I know type=number works but that is not what i want. my HTML:
<FormItem style={{ display: "inline-block" }}>
{getFieldDecorator('matchPercentage', {
initialValue: this.state.matchPercentage
})(
<Input type="number" value={this.state.matchPercentage} onChange={this.handlePercentMatch} style={{ width: 100, marginLeft: 10 }} />
)}
</FormItem>
我的功能:
handlePercentMatch = (e) => {
const isInteger = /^[0-9]+$/;
if (e.target.value === '' || isInteger.test(e.target.value)) {
this.setState({ matchPercentage: e.target.value })
}
}
我的 isInteger.test()
正在工作,这意味着我只能在状态下的 matchPercentage
中获取整数.但是问题是它没有反映在GUI中.即使未设置字母,我仍然可以键入字母.
My isInteger.test()
is working meaning I am able to get only integers in matchPercentage
in state. But the problem is It is not reflecting in GUI. I am still able to type alphabets even though they are not being set into state.
我知道type ="number"有效,但这不是我想要的.我想使用react进行验证,因为我希望控制小数位以及最多几位数字和非负数
I know type="number" works but that is not what i want. I want to validate using react as i want control decimals and upto how many digits and non negative
我在这里添加了我的代码 https://codepen.io/DadyByte/pen/xYgLvy?editors=1010
I have added my code here https://codepen.io/DadyByte/pen/xYgLvy?editors=1010
我找到了根本原因.如果您使用
FormItem
,则无论如何您都可以键入.如果我在FormItem之外使用Input
,则我的代码有效.我该怎么办
I found the root cause. If you use
FormItem
you will be allowed to type no matter what. If I useInput
outside FormItem my code is working. What can I do to prevent it
推荐答案
Ant Design具有InputNumber组件.您可以使用类似的东西
Ant Design has an InputNumber Component. You could use something like this
import {InputNumber} from 'antd';
用法
<InputNumber placeholder="Age (Max Age :100, Min Age:1)" size={'large'} min={1} max={100} onChange={this.handleAgeChange} />
然后您的handleAgeChange功能看起来像
Then your handleAgeChange Functionality could look like
handleAgeChange = (value) => {
this.setState((prevState) => (
{ ...prevState, age:value }
));
};
这篇关于在React(antd样式)的Input中仅允许数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!