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

Antd InputNumber输入时实时替换逗号为圆点的实现求助

解决Antd InputNumber实时替换逗号为圆点的问题

方案一:拦截按键实时替换

直接监听键盘事件,拦截逗号输入并替换为圆点,确保用户看不到逗号:

<InputNumber
  controls={false}
  placeholder="0"
  readOnly={isLoadingCurrencies}
  onChange={send.onAmountChangeDebounced}
  onKeyDown={(e) => {
    if (e.key === ',') {
      e.preventDefault();
      const input = e.target;
      const start = input.selectionStart;
      const end = input.selectionEnd;
      // 插入圆点并保持光标位置
      const newValue = input.value.slice(0, start) + '.' + input.value.slice(end);
      input.value = newValue;
      send.onAmountChangeDebounced(newValue);
      // 光标移到插入的圆点后面
      setTimeout(() => input.setSelectionRange(start + 1, start + 1), 0);
    }
  }}
/>

方案二:监听输入事件实时修正

通过原生input的input事件,实时替换输入内容里的逗号:

<InputNumber
  controls={false}
  placeholder="0"
  readOnly={isLoadingCurrencies}
  onChange={send.onAmountChangeDebounced}
  ref={(ref) => {
    if (!ref) return;
    const inputEle = ref.input;
    const handleInput = (e) => {
      const val = e.target.value;
      if (val.includes(',')) {
        const newVal = val.replace(',', '.');
        e.target.value = newVal;
        send.onAmountChangeDebounced(newVal);
        // 如果用了Form组件,同步字段值
        // form.setFieldValue('你的字段名', newVal);
      }
    };
    inputEle.addEventListener('input', handleInput);
    // 组件卸载时清理事件
    return () => inputEle.removeEventListener('input', handleInput);
  }}
/>

补充说明

  • 要是用了Form组件,在替换值后记得调用form.setFieldValue同步表单状态,避免值不一致
  • 防抖函数send.onAmountChangeDebounced要能处理高频触发的情况,可适当调整防抖延迟

内容的提问来源于stack exchange,提问作者howard wolowitz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:28:21