[英]React.JS How to allow only digits to be typed in input with '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>
像往常一样验证不是更好吗?
const {useState} = React; const r = /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/ const PhoneInput=() => { const [value,setValue]=useState(null); const [validated,setValidated]=useState(false); const onChange=(e)=>{ e.preventDefault(); let v = e.target.value; setValidated(!!v.match(r)); }; return ( <fieldset> <input type="text" value={value} onChange={onChange} ></input> <button disabled={!validated}> Send </button> </fieldset> ); }; ReactDOM.render(<PhoneInput />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.