【问题标题】:React.JS How to allow only digits to be typed in input with 'onKeyPress'React.JS如何只允许使用'onKeyPress'在输入中输入数字
【发布时间】:2021-09-05 05:48:18
【问题描述】:

我正在开发我的 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."
而且我知道为什么,只是想清楚我尝试了很多解决方案。

感谢帮助者

【问题讨论】:

    标签: javascript reactjs validation input user-input


    【解决方案1】:

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

    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>

    【讨论】:

    • 感谢@tevemadar 的工作,非常感谢!
    【解决方案2】:

    像往常一样验证不是更好吗?

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-05
      • 2018-03-06
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      相关资源
      最近更新 更多