如何防止用户在反应中输入负数? [英] How to prevent user from entering negative number in react?

查看:29
本文介绍了如何防止用户在反应中输入负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制用户输入负值.我正在使用 min = 0".有了这个,我可以限制用户递减到 0,即用户只能递减值到 0.但他们可以输入-".如何在 react js 中防止.

https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js

<输入类型=数字"min=0"步骤=1"onChange={this.handleChange}类名=w-100";值=1"/>

解决方案

Handling Empty Input &负数

//将 App 转化为 Class-Component类 App 扩展了 React.Component {//设置状态构造函数(道具){超级(道具);this.state = {号码:"};}使成为() {返回 (

<输入类型=数字"min=0"步骤=1"onChange={(e) =>{让 val = parseInt(e.target.value, 10);如果(isNaN(val)){this.setState({ number: "" });} 别的 {//是一个数字val = val >= 0 ?价值:0;this.setState({ number: val });}}}类名=w-100";//分配状态值={this.state.number}/>

);}}

I want to restrict users from entering negative values. I am using min = "0". With this i can restrict users from decrementing to 0, i.e, users can only decrement value till 0. But they are able to type "-". How to prevent in react js.

https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js

<input
   type="number"
   min="0"
   step="1"                        
   onChange={this.handleChange}                        
   className="w-100"
   value= "1"
   />

解决方案

Handling Empty Input & Negative Numbers

// Converting App into Class-Component
class App extends React.Component {
  // Set State
  constructor(props) {
    super(props);
    this.state = {
      number: ""
    };
  }

  render() {
    return (
      <div className="App">
        <input
          type="number"
          min="0"
          step="1"
          onChange={(e) => {
            let val = parseInt(e.target.value, 10);
            if (isNaN(val)) {
              this.setState({ number: "" });
            } else {
              // is A Number
              val = val >= 0 ? val : 0;
              this.setState({ number: val });
            }
          }}
          className="w-100"
          // Assign State
          value={this.state.number}
        />
      </div>
    );
  }
}

这篇关于如何防止用户在反应中输入负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆