【问题标题】:React isNaN with input type number用输入类型号反应 isNaN
【发布时间】:2020-03-17 17:59:08
【问题描述】:

在我的 React Hooks 应用程序中使用 useState 存储值之前,我需要检查 NaN,但它似乎没有检查?

const handleStartValueChange = (value) => {
        if (isNaN(parseInt(value)) ) {
            setStartValue(0);
        }
        setStartValue(parseInt(value));
    };

在类型为 number 的输入框上从 onChange 调用

<div className="startValueHeader">Start value</div>
                        <input
                            value={startValue}
                            type="number"
                            className="startValueValue"
                            onChange={(event) => {
                                handleStartValueChange(event.target.value);
                            }}
                        />

我错过了什么?

我需要检查 NaN 的原因是我需要在清除输入字段时存储一个值 0 而不是 ''

【问题讨论】:

  • console.log(value) 添加到handleStartValueChange 中,看看你实际得到了什么
  • parseInt(value) 总是将字符串转换为数字。并且 type=number 不允许字符串输入
  • 那为什么我会在 DOM 中得到 NaN?
  • 在setStartValue(0)后添加return语句;

标签: reactjs nan


【解决方案1】:

Number - convert numeric strings and null to numbers

Number('123')     // 123
Number('12.3')    // 12.3
Number('12.00')   // 12
Number('123e-1')  // 12.3
Number('')        // 0 <--- you need this
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity
const handleStartValueChange = value => {
  const number = Number(value); // converts '' from empty input -> 0
  setStartValue(number)
};

注意:如果您改为指定defaultValue,则输入为空时不会显示“0”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2020-02-18
    • 2019-03-10
    • 1970-01-01
    相关资源
    最近更新 更多