React 中只允许输入中的数字(antd 样式) [英] 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 样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!