ReactJs:重置表单后如何将焦点返回到输入字段

时间:2019-07-02 12:29:57

标签: reactjs autofocus

重置字段后如何将焦点重新设置为输入字段?

谢谢

//代码

<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 个答案:

答案 0 :(得分:2)

对于类组件

您应该将参考传递给输入

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

并在输入参考上获取集合.focus

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

对于功能组件

您应该使用useRef钩子。

const inputRef = useRef(null);

inputRef传递到input

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

然后使用.focus(指向已安装的输入元素)在输入ref上获取集合current

const resetForm = () => {   
    inputRef.current.focus()
}

答案 1 :(得分:0)

对输入元素使用自动对焦:

db.myCollection.find( .... == "paid" )
# result
{
  _id: id_1,
  status: {"random_key_1"=>"paid"}
}

在重置点击时调用

  <input autoFocus />