如何在 handlechange 中获取 formvalues?

How to get formvalues in handlechange?

在我的表单中,我在其中一个表单域上有一个 onChange 事件:

        <div>
            <label>Last Name</label>
            <div>
                <Field
                    name="lastName"
                    component="input"
                    type="text"
                    placeholder="Last Name"
                    onChange={() => this.handleChange()}
                />
            </div>
        </div>

当 handleChange 被解雇时,我想获取表单值:

handleChange(){
        //do calculation
        console.log('handlechange',this.props.values)        
    }

目前我得到 this.props.values = undefined?我怎样才能得到表格值?

  1. 您需要创建自定义 input
  2. 你需要拦截和更新 redux 的 input.onChange 函数。
  3. Optional -- 如果您希望其他表单值影响此值,请使用 reduxForm 的 formSelectorreact-reduxconnectmapStateToProps 访问 this.props 中组件内的 formProps(下面的工作示例已经包含此功能)

components/CustomInput.js

import React from "react";

const CustomInput = ({
  // we'll intercept redux's "onChange" func, while leaving the other 
  // input props as is in "inputProps"
  input: { onChange, ...inputProps }, 
  // the "handleChange" func below is the parent func that will handle input changes
  handleChange, 
  // "rest" contains any additional properties (className, placeholder, type ...etc)
  ...rest 
}) => (
  // we spread out the "inputProps" and the "rest" of the props, then we add
  // an "onChange" event handler that returns the "event" and the 
  // input's "onChange" func to our "handleChange" parent func
  <input {...inputProps} {...rest} onChange={e => handleChange(e, onChange)} />
);

export default CustomInput;

containers/Form.js

class ControlledFormValue extends PureComponent { 

  // this parent func will handle updates through the "event.target.value"; 
  // the value can be changed/altered and then passed to the input's
  // "onChange" func to update the field
  handleChange = ({ target: { value } }, onChange) => {
    // this will alter the value by adding a "-" after each input update
    onChange(`${value}-`);
    setTimeout(() => console.log(this.props.values), 500);
  };

  render() {
    return (
      <form onSubmit={this.props.handleSubmit}>
        <div>
          <label>First Name</label>
          <div>
            <Field
              className="uk-input"
              name="firstName"
              component={CustomInput}
              type="text"
              placeholder="First Name"
              handleChange={this.handleChange}
            />
          </div>
        </div>
        ...etc
     </form>
    );
  }
}

工作示例https://codesandbox.io/s/lx1r4yjwy7