首页 > 解决方案 > React.JS如何只允许使用'onKeyPress'在输入中输入数字

问题描述

我正在开发我的 ReactJS 新网站,我希望输入允许用户只输入手机号码的数字。

  onlyNumberKey = (event) => {
    let ASCIICode = event.which ? event.which : event.keyCode;
    if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57)) 
    return false;
    return true;
  };

 <div>
    <input type='text' onKeyPress='return {this.onlyNumberKey}' />
    </div>

我使用在我为我的问题发现的许多网站中找到的“onlyNumberKey”函数。
这个功能正在工作,并且会根据需要返回 true 或 false
但我可能不明白,如何防止用户插入字母和特殊字符?

这不起作用并给出错误 -

 onKeyPress='return this.onlyNumberKey' 

"Warning: Expected onKeyPress listener to be a function, instead got a value of string type."
我知道为什么,只是为了清楚我尝试了很多解决方案。

感谢帮助者

标签: javascriptreactjsvalidationinputuser-input

解决方案


您可以在更改处理程序中过滤掉不需要的字符:

class Test extends React.Component {
  constructor(){
    super();
    this.state = {
      input: ''
    };
  }

  onChangeHandler(e){
    this.setState({
      input: e.target.value.replace(/\D/g,'')
    });
  }

  render (){
    return (
      <input value={this.state.input} type="text" onChange={this.onChangeHandler.bind(this)}/>
    );
  }
}

ReactDOM.render(
  <Test />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


推荐阅读