如何使用redux-form进行受控输入?

时间:2018-03-04 18:24:09

标签: reactjs redux-form

我有一个表单组件,其中我们有一个输入字段。用户输入一个数字输入字段并按提交,它应该成为该输入值的两倍。

import {Field} 'redux-form'; 
class Multiply extends React.Component {

  onInputChange = (stateKey) => (e) => {
    this.setState({ [stateKey]: e.currentTarget.value.trim() });
  };

  onSubmit = () => {
    this.setState({ volume: this.state.volume *2  });
  };

  render(): JSX.Element {
    return (
      <div>
        <div>
          <form onSubmit={this.props.handleSubmit(this.onSubmit)}>
            <Field
              name="volume"
              placeholder="Volume"
              component={renderInput}
              type="number"
              value={this.state.volume}
              onChange={this.onInputChange('volume')}
              validate={required}
            />

            <div>
              <button type="submit">
                Multiply by 2
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

一旦我点击按钮,值就不会改变。但如果我使用<field>而不是<input>,那么它可以正常工作。为什么?

1 个答案:

答案 0 :(得分:1)

Redux表单输入由Redux状态决定。这意味着您必须使用其API来处理它们,因为Field为您的renderInput函数提供的输入值等于该字段名称的Redux存储中的任何值。

您需要做的是

  1. 注入字段值。这样做的好方法是使用formValues()
  2. 注入一个为该表单和该字段分派change action的函数
  3. 在按钮中调用此功能。
  4. 这是它的要点:

    const MyForm = ({ double }) => {
        /* Your form implementation, then */
        <button type="submit" onClick={double}>Double and submit</button>
    };
    
    const mapDispatchToProps = (dispatch, props) => ({
        double: () => dispatch(change("foo", "number", props.number * 2))
    });
    
    const WithDoublingFunction = formValues("number")(connect(null, mapDispatchToProps)(MyForm));
    
    export default reduxForm({
        form: "foo",
        // the rest of your config
    })(WithDoublingFunction);
    

    Here's a working sandbox of such functionality