In my form I have an onChange event on one of the formfields:
<div>
<label>Last Name</label>
<div>
<Field
name="lastName"
component="input"
type="text"
placeholder="Last Name"
onChange={() => this.handleChange()}
/>
</div>
</div>
When handleChange gets fired I want to get the formvalues :
handleChange(){
//do calculation
console.log('handlechange',this.props.values)
}
At the moment I am getting this.props.values = undefined? How can I get the formvalues?
- You'll need to create a custom
input
. - You'll need to intercept and update redux's
input.onChange
function. - Optional -- If you want other form values to influence this value, then utilize reduxForm's
formSelector
withreact-redux
'sconnect
'smapStateToProps
to access formProps within the component inthis.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
来源:https://stackoverflow.com/questions/55435964/how-to-get-formvalues-in-handlechange