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

React Final Form结合react-number-format失焦时同步更新值

解决react-number-format与react-final-form的前导零值同步问题

这个问题我之前在项目里碰到过,核心原因是react-number-format通过allowLeadingZeros实现的失焦去前导零操作,属于组件内部的数值修正,不会触发我们绑定的onChange回调,所以react-final-form存储的值没法同步更新。给你两个靠谱的解决办法:

方法一:使用onValueChange替代onChange

react-number-format提供了onValueChange回调,它会在所有值变化场景(包括用户输入、组件内部修正)触发,能直接拿到处理后的标准化数值。我们可以利用它来同步react-final-form的值:

const CurrencyInput = props => {
  return (
    <NumberFormat
      thousandSeparator=" "
      decimalScale="2"
      isNumericString={true}
      fixedDecimalScale={true}
      allowNegative={false}
      autoComplete="off"
      onBlur={props.input.onBlur}
      onFocus={props.input.onFocus}
      // 改用onValueChange获取处理后的值
      onValueChange={(values) => {
        // values.floatValue是格式化后的数值类型,formattedValue是带千分符的字符串类型
        // 根据你的需求选择其中一个传给final-form
        props.input.onChange(values.floatValue ?? values.formattedValue);
      }}
    />
  );
};

这个方案是最推荐的,因为它完全贴合组件的设计逻辑,能覆盖所有值变化的场景,不需要额外的手动处理。

方法二:在onBlur中手动同步修正后的值

如果因为某些原因不想改用onValueChange,也可以通过ref获取react-number-format的当前值,在失焦时手动同步给react-final-form:

import { useRef } from 'react';

const CurrencyInput = props => {
  const formatRef = useRef(null);

  const handleBlur = () => {
    // 先触发final-form的onBlur逻辑
    props.input.onBlur();
    // 获取组件内部修正后的数值
    const correctedValue = formatRef.current?.getInputValue();
    if (correctedValue) {
      props.input.onChange(correctedValue);
    }
  };

  return (
    <NumberFormat
      ref={formatRef}
      thousandSeparator=" "
      decimalScale="2"
      isNumericString={true}
      fixedDecimalScale={true}
      allowNegative={false}
      autoComplete="off"
      onBlur={handleBlur}
      onFocus={props.input.onFocus}
      onChange={value => props.input.onChange(value)}
    />
  );
};

这种方式的核心是利用组件的getInputValue()方法拿到修正后的真实值,在失焦时主动同步给表单,确保final-form存储的值和输入框显示一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:36:24