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
相关产品推荐
相关产品推荐

