如何在reactjs中只允许文本框中的数字? [英] How to allow only numbers in textbox in reactjs?

查看:32
本文介绍了如何在reactjs中只允许文本框中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅使用正则表达式reactjs中只允许textbox中的数字?

How to allow only numbers in textbox in reactjs using regular expression only?

推荐答案

基本思路是:

使用受控组件(使用输入字段的值和onChange属性),并在 onChange 句柄内部检查输入的值是否为正确的数字.仅当输入的值是有效数字时才更新状态.

Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.

为此使用这个正则表达式:/^[0-9\b]+$/;

onChange 处理程序将是:

onChange handler will be:

onChange(e){
    const re = /^[0-9\b]+$/;

    // if value is not blank, then test the regex

    if (e.target.value === '' || re.test(e.target.value)) {
       this.setState({value: e.target.value})
    }
}

工作示例:

class App extends React.Component{
   constructor(){
      super();
      this.state = {value: ''};
      this.onChange = this.onChange.bind(this)
   }
   
   onChange(e){
      const re = /^[0-9\b]+$/;
      if (e.target.value === '' || re.test(e.target.value)) {
         this.setState({value: e.target.value})
      }
   }
   
   render(){
     return <input value={this.state.value} onChange={this.onChange}/>
   }
}

ReactDOM.render(<App/>,document.getElementById('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>

<div id='app'/>

这篇关于如何在reactjs中只允许文本框中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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