ReactJS - 仅输入 PropType 设置为数字但初始化为零的数字

ReactJS - number only input with PropType set to number but gets initialized to zero

我正在使用 ReactJS 并创建一个我只想允许数字的基本受控文本输入框。它受到控制,因此值是状态变量,onChange 更新状态。我还将 PropType 设置为一个数字。但是当我这样做时,我必须将状态变量初始化为零,然后输入框被预填充为零。显然这对用户来说不是很友好。想知道是否有人知道解决这个问题的方法。如果没有,我只需要将 PropType 更改为字符串即可。我确实找到了一个非常相似的问题和答案,但它特定于 Angular:

相关代码:

状态: const [lastPalletBagCount, setLastPalletBagCount] = useState(0);

输入:

<input
    type={'text'}
    className={'bag-count'}
    value={lastPalletBagCount}
    onChange={(e) =>
        setLastPalletBagCount(e.target.value)
    }
/>

道具类型: lastPalletBagCount: PropTypes.number.isRequired,

我觉得,

  const [lastPalletBagCount, setLastPalletBagCount] = React.useState<number>();

  const handler = (e: any) => {
    console.log(e.target.value)
    const numberregex = /^[0-9\b]+$/;

    if (numberregex.test(e.target.value)) {
      var val = Number(e.target.value);
      setLastPalletBagCount(val);

    }

  }

  return (
      <input
        type={'text'}
        className={'bag-count'}
        value={lastPalletBagCount}
        onChange={(e) =>
          handler(e)
        }
      />
  );

适合你。

但是您必须使用一些逻辑将 onchange 中事件中的值更改为数字,因为您的输入类型是字符串并且 return 一个字符串类型的值。

你可以这样做:

Comp.propTypes = {
  lastPalletBagCount: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([''])
  ]).isRequired
}