只有数字.在 React 中输入数字 [英] Only numbers. Input number in React

查看:31
本文介绍了只有数字.在 React 中输入数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从输入中排除减号和加号,但出错了:

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});
}

渲染输入代码:

<input style={{width: '150px'}} type="number" value={this.state.financialGoal} onChange={this.handleChange}/>

推荐答案

我尝试模仿您的代码,并注意到 React 上存在一个问题 <input type='number'/>.如需解决方法,请查看此示例并自行尝试:https://codepen.io/zvona/pen/WjpKJX?editors=0010

I tried to mimic your code and noticed that there's an issue on React with <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010

您需要将其定义为普通输入 (type='text'),仅用于数字模式:

You need to define it as normal input (type='text') with pattern for numbers only:

    <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.

这篇关于只有数字.在 React 中输入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆