簡體   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