Redux表示在不破坏表单初始化的情况下基于另一个字段更改一个字段值的方法(基于值)

时间:2018-01-18 11:33:29

标签: reactjs redux redux-form

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

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

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

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

那么Redux Form是什么方式来监听每个字段的onChange事件并根据它进行计算并更新其他字段内的值尽管仍然初始化具有初始值功能的表单?

1 个答案:

答案 0 :(得分: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之后