如何只允许reactjs中的文本框中的数字?

Sou*_*era 9 reactjs

如何允许只有数字textboxreactjs使用regular expression只?

May*_*kla 36

基本思路是:

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

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

onChange处理程序将是:

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})
    }
}
Run Code Online (Sandbox Code Playgroud)

工作范例:

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'))
Run Code Online (Sandbox Code Playgroud)
<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'/>
Run Code Online (Sandbox Code Playgroud)


Ric*_*las 21

一个简单的解决方案,使用钩子:

const [age, setAge] = useState();

const handleChange = (e) => {
  const value = e.target.value.replace(/\D/g, "");
  setAge(value);
};

return (
  <div>
    <input value={age} onChange={handleChange} />
  </div>
);
Run Code Online (Sandbox Code Playgroud)

示例: https: //codesandbox.io/s/adoring-minsky-9sqvv


abh*_*ake 7

Mayank Shukla提供的答案是正确的,毫无疑问.


但是,您可以使用默认的html属性而不是它type="number".

在这种情况下不需要使用正则表达式,因为<input type="number" value={this.state.value} onChange={this.onChange}/>只接受数字.

  • 它仍然允许一些特殊字符,如“e”、“.”、“-”等 (7认同)