ReactJs: Как вернуть фокус на поле ввода после сброса формы - PullRequest
0 голосов
/ 02 июля 2019

Как я могу установить фокус обратно на поле ввода после сброса поля?

Спасибо

// code

<div
            className={cn("input-border-wrapper", { "is-disabled": disabled })}
          >
            <input
              placeholder={label}
              required={optional === null ? !!required`${name}` : !optional}
              readOnly={readonly}
              aria-describedby={describedByIds}
              autoComplete={autocomplete`${name}`}
              inputMode={inputmode`${name}`}
              {...validations`${name}`}
              {...this.props.input}
              {...{ disabled, id }}
              type={type || inputtype`${name}` || "text"}
              ref={refCallback}
            />
          </div>
          {(optional === null ? !required`${name}` : optional) &&
            !hasValue && (
              <span className="input-wrapper--optional">{optionalLabel}</span>
            )}
          <InputIcon
            ariaLabel={buttonAriaLabel}
            hasClearIcon={
              shouldShowClearIcon && hasValue && (isActive || hasError)
            }
            hasCalendarIcon={
              button === "lh-datepicker" || icon === "lh-datepicker"
            }
            name={button || icon}
            onClick={onButtonClick}
            onMouseDown={() => clearInputValue(form, name, "")
            }
            {...{ disabled, hasIcon, hasButton }}
          />

Ответы [ 2 ]

2 голосов
/ 02 июля 2019

для компонентов класса

Вы должны перейти на вход ref

<input ref={inputRef => this.inputRef = inputRef } {...} />

И получить набор .focus на входе ref.

resetForm = () => {
    this.inputRef.focus()
}

Для функциональных компонентов

Вы должны использовать useRef крючок.

const inputRef = useRef(null);

Пропуск inputRef на input

<input ref={inputRef} {...} />

И получите набор .focus на входной ссылке, используя current (который указывает на смонтированный элемент ввода).

const resetForm = () => {   
    inputRef.current.focus()
}
0 голосов
/ 02 июля 2019

Использовать автофокус с элементом ввода:

  <input autoFocus />

позвоните при сбросе нажмите

  formReset(){
    this.focus();
  }
...