Answer the question
In order to leave comments, you need to log in
Why is Redux Field not firing onChange?
I call the Field component from redux-form:
<Field
id={'form__file'}
className={'form__file form__control'}
name={'photo'}
type={'file'}
label={'Upload your photo'}
accept={'image/jpeg,image/jpg'}
component={FileInput}
onChange={onFileInputChange}
/>
export class FileInput extends Component {
onChange = e => { // это никогда не срабатывает
e.preventDefault();
const { input: { onChange } } = this.props;
onChange(e.target.files[0]);
};
render() {
let {meta: {touched, error}, ...props} = this.props;
return (
<>
<Form.File
custom
{...props.input}
id={props.id}
className={props.className}
label={props.label}
onChange={this.onChange}
type={props.type}
accept={props.accept}
/>
{touched && error && (
<Form.Text className="form__error form__text">
{error}
</Form.Text>
)}
</>
)
}
};
onFileInputChange = (e) => {
e.preventDefault();
this.setState({photo: e.target.files[0]});
console.log(e.target.files[0]);
};
<Form.File
id={'form__file'}
className={'form__file form__control'}
name={'photo'}
type={'file'}
label={'Upload your photo'}
accept={'image/jpeg,image/jpg'}
onChange={onFileInputChange}
custom
/>
Answer the question
In order to leave comments, you need to log in
Found what the problem is. The FileInput that was rendered by Field through the {...props.input} specification set the value for the field, but this cannot be done. You need to change it like this:
export class FileInput extends Component {
onChange = e => {
e.preventDefault();
const { input: { onChange } } = this.props;
onChange(e.target.files[0]);
};
render() {
let {meta: {touched, error}, input: {value}, ...props} = this.props; // достаем value из props.input
return (
<>
<Form.File
custom
{...props.input}
id={props.id}
className={props.className}
label={props.label}
onChange={this.onChange}
type={props.type}
accept={props.accept}
/>
{touched && error && (
<Form.Text className="form__error form__text">
{error}
</Form.Text>
)}
</>
)
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question