繁体   English   中英

redux-form格式输入仅适用于onBlur

[英]redux-form format input ONLY onBlur

在我的表格中,我有一个“金额”字段,应始终显示2位小数。 因此,例如,如果用户键入3,则应将其转换为3.00。 如果他输入3.1234525,它应该变成3.12。

为了做到这一点,我依靠onBlur道具。 基本上onBlur我运行一个正确格式化数字的函数,我尝试在字段上设置新值。

这是我的代码:

 import { blur as blurField } from 'redux-form/immutable'; ... const mapDispatchToProps = { blurField, }; ... export default connect(mapStateToProps, mapDispatchToProps)(Amount); 

class AmountContainer extends Component {
    props: PaymentMethodPropsType;

    formatAmount(event) {
        const {
            blurField,
        } = this.props;
        blurField('myForm', 'amount', formatNumber(event.currentTarget.value, 2));
    }

    /**
     * Render method for the component
     * @returns {Element<*>} the react element
     */
    render() {
        const {
            t,
            amountValue,
        } = this.props;

        const amountLabel = t('form')('amountLabel');

        return (
            <Amount
                amountLabel={amountLabel}
                amountValue={amountValue}
                normalize={onlyNumbersDecimals}
                onBlur={(event: Event) => this.formatAmount(event)}
                validation={[
                    isRequired(t('validation')('amountRequired')),
                    number(t('validation')('amountNotNumber')),
                ]}
            />
        );
    }
}

假设我输入数字3,然后移动到表单中的下一个字段。 我可以看到调用以下操作:

{type: "@@redux-form/BLUR", meta: {…}, payload: "3.00"}
{type: "@@redux-form/BLUR", meta: {…}, payload: "3"}

结果输入值保持为3.看起来初始的onBlur事件“覆盖”我触发的调用blurField

只需使用event.preventDefault就可以了:

formatAmount(event) {
    const {
        blurField,
    } = this.props;
    event.preventDefault();
    blurField('myForm', 'amount', formatNumber(event.currentTarget.value, 2));
}

嘿所以这有点晚了,但我找到了一种有效而简单的方法来解决这个问题。 我发送on blur prop,将函数绑定到表单作用域,并使用内置的redux-form函数(更改)使用格式化的值更新字段值。 这项技术的有趣之处在于,您需要使用setTimeout将执行时间设置为0,以使其正常工作。 恩。

onBlur={e => {
  let value = e.target.value;
  * Format or update value as needed *
  setTimeout(() => this.props.change(* FIELD NAME *, value));
}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM