【问题标题】:Redux Form way of changing one Field's value based on another Field without breaking Form Initialisation (based on values)Redux Form 基于另一个字段更改一个字段的值而不破坏表单初始化的方法(基于值)
【发布时间】:2018-01-18 11:33:28
【问题描述】:

这是我为我的问题创建的沙盒: https://codesandbox.io/s/rrx4648y9q

当用户为纬度十进制字段输入十进制值时,我想将十进制值转换为度、分和秒,并填充纬度度、纬度分和纬度秒字段,反之亦然。

在我之前没有使用 Redux Form 的代码中,我会通过为每个字段的 onChange 属性设置一个函数来做到这一点。然后在该函数内部,我将进行计算并使用 this.setState 更新状态内的值,然后每个字段的值将取决于该状态,因此每个字段将根据计算更新为新值。

但是,由于我使用的是 Redux Form 并且我还使用 Redux Form 的 Initialise Form With Values 功能,如果我将自己的函数设置为 onChange 属性,则会破坏该功能。如果我还为每个字段的 value 属性设置了一个值,那么我将无法编辑字段。

那么 Redux Form 监听每个字段的 onChange 事件并基于该事件进行计算并更新其他字段内的值的方式是什么,同时仍具有初始化表单的初始值功能正常工作?

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    您可以创建 HOC 来处理表单更改。比如

    import React from 'react';
    import PropTypes from 'prop-types';
    import {formValues} from 'redux-form';
    
    export const withSyncFormValues = (WrappedElement) => {
        class WithSyncFormValues extends React.PureComponent {
            propTypes = {
                autofill: PropTypes.func.isRequired,
                exampleFormValue: PropTypes.any
            }
    
            componentWillReceiveProps(nextProps) {
                // Sync logic like
                // Autofill props provided by ReduxForm
                // https://redux-form.com/7.2.1/docs/api/props.md/#-code-autofill-field-string-value-any-function-code-
                if (nextProps.exampleFormValue !== this.props.exampleFormValue) {
                    this.props.autofill('relatedFormValue', 'newValue');
                }
            }
    
            render() {
                // Also you can omit exampleFormValue from props there
                return (
                    <WrappedElement {...this.props} />
                );
            }
        }
        // https://redux-form.com/7.2.1/docs/api/formvalues.md/
        return formValues('exampleFormValue')(WithSyncFormValues);
    }
    

    并像使用它

    reduxForm(formProperties)(withSyncFormValues(YourFormComponent))
    

    或使用装饰器

    @reduxForm(formProperties)
    @withSyncFormValues
    class YourFormComponent extends React.PureComponent { ..... }
    

    重要的是要记住 withSyncFromValues 必须在 reduxForm 之后

    【讨论】:

      猜你喜欢
      • 2015-04-09
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多