V
V
Vladimir Golub2019-04-16 11:23:36
React
Vladimir Golub, 2019-04-16 11:23:36

Can't change input with value from state?

After setting value through state, I can't change it manually, how can I fix it?

<input
                        onChange={(event) => this.handlerInputChange(event.target.value)}
                        value={this.state.dateInput}/>

    handlerInputChange = (date) => {

        let dateRegExp = /([0-9]{2}.[0-9]{2}.[0-9]{4})/,
            resultMatch,
            dateDelivery;

        let {
            minDate,
            maxDate
        } = this.props;

        resultMatch = date.match(dateRegExp);

        if (resultMatch && resultMatch.length > 0) {
            dateDelivery = new Date(resultMatch[1].replace(/([0-9]{2}).([0-9]{2}).([0-9]{4})/, '$3-$2-$1'));

            if (dateDelivery && (minDate && dateDelivery < minDate || maxDate && dateDelivery > maxDate)) {
                return false;
            }

            this.setState({
                date: moment(dateDelivery),
                dateInput: resultMatch[1]
            });

            this.props.onChange(resultMatch[1] ? resultMatch[1] : "");
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Golub, 2019-04-16
@RazerVG

The solution to the problem turned out to be simple, after each field change, you need to change the state

handlerInputChange = (event) => {
        console.log('Срабатывание функции handlerInputChange ');
        console.log('Переданное значение: ', event.target.value);

        event.preventDefault();

        this.setState({
            date: null,
            dateInput: event.target.value
        })

        let dateRegExp = /([0-9]{2}.[0-9]{2}.[0-9]{4})/,
            resultMatch,
            dateDelivery;

        let {
            minDate,
            maxDate
        } = this.props;

        resultMatch = event.target.value.match(dateRegExp);

        if (resultMatch && resultMatch.length > 0) {
            console.log('Задание state');

            dateDelivery = new Date(resultMatch[1].replace(/([0-9]{2}).([0-9]{2}).([0-9]{4})/, '$3-$2-$1'));

            if (dateDelivery && (minDate && dateDelivery < minDate || maxDate && dateDelivery > maxDate)) {
                console.log('Ошибка');
                return false;
            }

            this.setState({
                date: moment(dateDelivery),
                dateInput: resultMatch[1]
            });

            this.props.onChange(resultMatch[1] ? resultMatch[1] : "");
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question