В моей форме у меня есть событие onChange в одном из полей формы:
<div>
<label>Last Name</label>
<div>
<Field
name = "lastName"
component = "input"
type = "text"
placeholder = "Last Name"
onChange = {() => this.handleChangeEvent()}
/>
</div>
</div>
Когда handleChangeEvent запускается, я хочу получить значения формы:
handleChangeEvent(){
//do calculation
console.info('handlechange',this.props.values)
}
На данный момент я получаю this.props.values = undefined? Как я могу получить значения формы?





input.input.onChange.formSelector с react-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 "handleChangeEvent" func below is the parent func that will handle input changes
handleChangeEvent,
// "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 "handleChangeEvent" parent func
<input {...inputProps} {...rest} onChange = {e => handleChangeEvent(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
handleChangeEvent = ({ target: { value } }, onChange) => {
// this will alter the value by adding a "-" after each input update
onChange(`${value}-`);
setTimeout(() => console.info(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"
handleChangeEvent = {this.handleChangeEvent}
/>
</div>
</div>
...etc
</form>
);
}
}
Рабочий пример: https://codesandbox.io/s/lx1r4yjwy7
Обновленный пример выше и файл codeandbox. Измените ввод, и он распечатает текущие значения формы. Все, что вам нужно сделать, это добавить getFormValues к mapStateToProps. Просто обратите внимание, что mapStateToProps — это asynchronous, поэтому вам придется ждать обновлений (отсюда и setTimeout).
Я искал решение с getFormValues, потому что я использую FieldArray. Значения формы — это список строк, в каждой строке объект, представляющий строку. Я действительно упростил вопрос.