Skip to content

setFocus

手动设置输入焦点

setFocus: (name: string, options: SetFocusOptions) => void

此方法将允许用户以编程方式专注于输入。确保输入的引用已注册到钩子表单中。

¥This method will allow users to programmatically focus on input. Make sure input's ref is registered into the hook form.

属性

¥Props


名称类型描述
namestring要聚焦的输入字段名称
optionsshouldSelectboolean是否选择焦点输入内容。
RULES
  • 该 API 将从 ref 调用 focus 方法,因此在 register 期间提供 ref 非常重要。

    ¥This API will invoke focus method from the ref, so it's important to provide ref during register.

  • 避免在 reset 之后立即调用 setFocus,因为所有输入引用都将被 reset API 删除。

    ¥Avoid calling setFocus right after reset as all input references will be removed by reset API.

示例

¥Examples


import * as React from "react"
import { useForm } from "react-hook-form"
type FormValues = {
firstName: string
}
export default function App() {
const { register, handleSubmit, setFocus } = useForm<FormValues>()
const onSubmit = (data: FormValues) => console.log(data)
renderCount++
React.useEffect(() => {
setFocus("firstName")
}, [setFocus])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} placeholder="First Name" />
<input type="submit" />
</form>
)
}
import * as React from "react"
import { useForm } from "react-hook-form"
export default function App() {
const { register, handleSubmit, setFocus } = useForm()
const onSubmit = (data) => console.log(data)
renderCount++
React.useEffect(() => {
setFocus("firstName")
}, [setFocus])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} placeholder="First Name" />
<input type="submit" />
</form>
)
}
React Hook Form 中文网 - 粤ICP备13048890号