Почему при первом запуске мой ввод вводится в ноль? - PullRequest
0 голосов
/ 02 апреля 2020

У меня есть существующая редукс-форма с полями, которыми я должен манипулировать. Я добавляю стили css в существующую форму перед onSubmit, используя document.add.classList. С этим я говорю форме добавить css -errors ('form-invalid', 'simple-form') после первого запуска, это очень хорошо работает. Теперь мне нужно сделать то же самое с полями (входы и метка используют внешние css), но на первом проходе input равен NULL, поэтому я не могу удалить класс ('error'), который мне нужно удалить до того, как ввод был коснулся или сосредоточился. Моя цель - заставить поля выглядеть «нейтральными» при первом рендеринге. Как сейчас, они работают нормально, но с самого начала показывают красные метки, и для меня нет особого смысла показывать ошибки, прежде чем пользователь что-то наберет.

Есть ли способ добиться того, что мне нужно?

Это мой компонент для поля формы-редукса:

renderField = ({
        input,
        id,
        name,
        customMobile,
        type,
        placeholder,
        meta: { error, dirty },
    }) =>
        customMobile ? (
            <div className="container_custom">
                <div className="group_custom">
                    <input
                        {...input}
                        id={id}
                        className={`custom_mobile ${error ? 'error' : null}`}
                        type={type}
                        onKeyDown={this._handleKeyDown}
                        onFocus={this._addErrorClassToForm(error, dirty, id)}
                        dirty={dirty.toString()}
                        required
                    />{' '}
                    <span className="highlight"></span>
                    <span className="bar"></span>
                    <label htmlFor={name} className="custom_mobile">
                        {placeholder}
                    </label>
                </div>
            </div>
        ) : (
            <input
                {...input}
                className={error ? 'error' : null}
                placeholder={placeholder}
                type={type}
            />
        )

Это функция, которую я сделал, чтобы добавить и удалить css, вызывая classList (как уже упоминалось, класс 'error' в Fields отсутствует удалено, потому что на первом проходе вход равен NULL:

_addErrorClassToForm = (error, dirty, id) => {
    var form = document.getElementById('form-abschluss')
    var input = document.getElementById(id)
    if (dirty) {
        if (error) {
            form.classList.add('form-invalid', 'simple-form')
            input.classList.add('error')
        } else if (!error) {
            form.classList.remove('form-invalid', 'simple-form')
            input.classList.remove('error')
        }
    } else {
        input.classList.remove('error')
        return
    }
}

И это одно из полей в форме:

 <Field
                            name="email"
                            id="email"
                            component={this.props.renderField}
                            type="email"
                            placeholder="E-Mail-Adresse"
                            onChange={this.props.addToCookie}
                            customMobile={true}
                        />

А вот мой css для отображения новых входов Поведение:

input.custom_mobile {
    font-family: 'Poppins';
    font-size: 18px;
    padding: 20px 10px 4px 5px;
    display: block;
    width: 100%;
    height: 40px !important;
    border: none;
    border-bottom: 0.5px solid #757575;
}

input.custom_mobile:focus {
    outline: none;
}

select.custom_mobile {
    font-family: 'Poppins';
    font-size: 18px;
    padding: 20px 10px 0px 5px;
    display: block;
    width: 100%;
    height: 40px !important;
    border: none;
    border-bottom: 0.5px solid #757575;
}

select.custom_mobile:focus {
    outline: none;
}

/* LABEL ======================================= */
label.custom_mobile,
input.custom_mobile ~ label.custom_mobile {
    color: #696969;
    font-family: 'Poppins';
    font-size: 18px;
    font-weight: normal;
    position: absolute;
    pointer-events: none;
    left: 5px;
    top: 20px;
    transition: 0.2s ease all;
    -moz-transition: 0.2s ease all;
    -webkit-transition: 0.2s ease all;
}

/* active state */
input.custom_mobile:focus ~ label.custom_mobile,
input.custom_mobile:valid ~ label.custom_mobile {
    top: -10px;
    font-size: 14px;
    color: $cerulean;
}

input.custom_mobile.error ~ label.custom_mobile {
    top: -10px;
    font-size: 15px;
    color: $dark-pink;
    background: #ffffff;
    padding: 0 2px;
    z-index: 200;
}

Я очень много боролся с этим. Любая помощь будет высоко ценится! *

1 Ответ

0 голосов
/ 03 апреля 2020

Решено с помощью псевдоклассов input.custom_mobile.error:placeholder-shown

...