isNan()和typeof无法与React一起使用

时间:2019-04-22 00:49:15

标签: javascript reactjs react-bootstrap

我正在尝试在react-bootstrap组件上创建仅数字输入字段。我知道可以使用type =“ number”属性,但是将类型设置为password以屏蔽输入。

我一开始尝试过,但是没有用:

handleAcessCodeChange(event) {
    isNan(event.target.value) ? this.setState({ [event.target.id] : event.target.value }) : console.log('Non-numeric input');
}

然后我尝试了很长的路,但仍然行不通:

if(isNaN(event.target.value)) {
  this.setState({ [event.target.id] : event.target.value });
}
else {
  event.preventDefault();
  console.log('Error');
}
{/* Access code */}
<Form.Group controlId='accessCode'>
    <Form.Label>Access Code</Form.Label>
    <Form.Control
      style={{ width: '50%' }}
      type='password'
      placeholder='Enter access code'
      defaultValue=''
      autocomplete='off'
      value={this.state.accessCode}
      onChange={this.handleAcessCodeChange.bind(this)}
    />
</Form.Group>

如果输入了非数字输入但我接受了所有内容,我希望页面显示错误。我的代码是否有问题,或者是引导程序组件的实现?

1 个答案:

答案 0 :(得分:0)

我知道这是在不久前被问到的,但是当我寻找答案时这个问题就出现了。

您可能要使用与全局isNaN(需要IE polyfill)不同的Number.isNaN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description

从MDN中检出其中一些示例:

isNaN(NaN);       // true
isNaN(undefined); // true
isNaN({});        // true

isNaN(true);      // false
isNaN(null);      // false
isNaN(37);        // false

// strings
isNaN('37');      // false: "37" is converted to the number 37 which is not NaN
isNaN('37.37');   // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN("37,5");    // true
isNaN('123ABC');  // true:  parseInt("123ABC") is 123 but Number("123ABC") is NaN
isNaN('');        // false: the empty string is converted to 0 which is not NaN
isNaN(' ');       // false: a string with spaces is converted to 0 which is not NaN

// dates
isNaN(new Date());                // false
isNaN(new Date().toString());     // true

// This is a false positive and the reason why isNaN is not entirely reliable
isNaN('blabla');   // true: "blabla" is converted to a number. 
                   // Parsing this as a number fails and returns NaN