使用输入类型编号反应 isNaN

React isNaN with input type number

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

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

这是在类型为数字的输入框上从 onChange 调用的

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

我错过了什么?

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

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”。