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

问题描述 投票:1回答:2

我正在使用ReactJS并创建一个我只希望允许数字的基本受控文本输入框。它受到控制,因此该值是状态变量,并且onChange更新状态。我还将PropType设置为一个数字。但是当我这样做时,我必须将状态变量初始化为零,然后输入框将被预填充为零。显然,这对用户不是很友好。想知道是否有人知道解决此问题的方法。如果没有,我只需要将PropType更改为字符串,然后就可以了。我确实找到了非常相似的问答,但它特定于Angular:AngularJS <input> with type set to 'number', how to force a initial display of value to a non-number string

相关代码:

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

输入:

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

属性:lastPalletBagCount: PropTypes.number.isRequired,

reactjs react-proptypes
2个回答
3
投票

您可以做:

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

0
投票

我认为,

  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事件中的值更改为number,因为您的输入类型是string,并且将返回string类型的值。

© www.soinside.com 2019 - 2024. All rights reserved.