本文介绍了在React(antd样式)的Input中仅允许数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道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.

我在这里添加了我的代码 https://codepen.io/DadyByte/pen/xYgLvy?editors=1010

I have added my code herehttps://codepen.io/DadyByte/pen/xYgLvy?editors=1010

推荐答案

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中仅允许数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 10:04