You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

小米设备上如何阻止MUI number类型TextField输入负数?

如何阻止小米设备上MUI数字类型TextField输入负数?

我在MUI的数字类型TextField中设置了min="1"来阻止输入负数,该设置在iPhone、三星设备及桌面端都能正常生效,但在小米Redmi 8 Pro上无效,无法阻止负数输入。

以下是验证有效的解决方法,通过监听onInput事件处理输入内容,过滤掉负数:

const handleNegativeValues = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (
      (e.nativeEvent as InputEvent).data &&
      (e.nativeEvent as InputEvent).data !== '.'
    ) {
      e.target.value =
        !!e.target.value && Math.abs(+e.target?.value) >= 0
          ? Math.abs(+e.target?.value).toString()
          : (value as string);
    }
  };

<TextField
      autoFocus
      onInput={handleNegativeValues}
      placeholder="00.00"
      size="medium"
      type="number"
      value={value}
      variant="outlined"
    />

方案说明:

  • value为存储在组件状态中的输入框当前值
  • 判断(e.nativeEvent as InputEvent).data !== '.'是为了保留小数点输入功能
  • 已在小米(Redmi 8 Pro)、iPhone、三星设备及桌面端测试验证有效

内容的提问来源于stack exchange,提问作者Tetiana Korshunova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:14:52