如何在handlechange中获取表单值?

IT技术 reactjs redux-form
2021-05-23 06:46:35

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

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

当 handleChange 被触发时,我想获取 formvalues :

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

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

1个回答
  1. 您需要创建一个自定义input.
  2. 您需要拦截并更新 redux 的input.onChange功能。
  3. 可选的-如果你想其他形式的value观来影响这个值,然后利用reduxForm的formSelectorreact-reduxconnectmapStateToProps访问formProps在组件内this.props(工作下面的例子已经包含了此功能)

组件/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;

容器/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