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
| 名称 | 类型 | 描述 | |
|---|---|---|---|
name | string | 要聚焦的输入字段名称 | |
options | shouldSelect | boolean | 是否选择焦点输入内容。 |
RULES
-
该 API 将从 ref 调用 focus 方法,因此在
register期间提供ref非常重要。¥This API will invoke focus method from the ref, so it's important to provide
refduringregister. -
避免在
reset之后立即调用setFocus,因为所有输入引用都将被resetAPI 删除。¥Avoid calling
setFocusright afterresetas all input references will be removed byresetAPI.
示例
¥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>)}