How to get formvalues in handlechange?

百般思念 提交于 2019-12-08 15:14:33
  1. You'll need to create a custom input.
  2. You'll need to intercept and update redux's input.onChange function.
  3. Optional -- If you want other form values to influence this value, then utilize reduxForm's formSelector with react-redux's connect's mapStateToProps to access formProps within the component in this.props (the working example below already includes this functionality)

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>
    );
  }
}

Working example: https://codesandbox.io/s/lx1r4yjwy7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!