javascript - 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."
我知道为什么,只是为了清楚我尝试了很多解决方案。
解决方案
您可以在更改处理程序中过滤掉不需要的字符:
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>
推荐阅读
- javascript - 将具有少量变量的静态 JS 函数转换为动态
- java - 当我点击一个recyclerview项目时,如何从一个片段移动到一个新的活动?
- kubernetes - 为什么必须为 ClusterRoleBinding.rbac.authorization.k8s.io 资源的 ServiceAccount 显式设置命名空间?
- oracle - PLSQL 文本文件创建行结束格式
- flutter - 错误:没有提供 AWSAccessKey - 颤振放大
- javascript - Danfo.js:使用 read_csv() 读取 .tsv 文件?
- python - 如果连续日期不存在,如何根据'ent_id'和'val'列在PANDAS中执行FFILL(),否则需要完成填充?
- android - 是否可以在没有数据库反应本机的情况下在 android / ios 中跟踪应用程序购买
- node.js - Discord.js Quick.db 过滤器
- java - 为什么在对父级使用paint方法后组件不可见