gpt4 book ai didi

reactjs - 如何使用 React-Hook-Form 设置 ref 焦点

转载 作者:行者123 更新时间:2023-12-03 14:42:00 25 4
gpt4 key购买 nike

您如何使用 React-Hook-Form 在输入中实现设置焦点,这是他们的常见问题解答中的“如何共享引用使用”代码 https://www.react-hook-form.com/faqs/#Howtosharerefusage

import React, { useRef } from "react";
import { useForm } from "react-hook-form";

export default function App() {
const { register, handleSubmit } = useForm();
const firstNameRef = useRef();
const onSubmit = data => console.log(data);

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={(e) => {
register(e)
firstNameRef.current = e // you can still assign to ref
}} />
<input name="lastName" ref={(e) => {
// register's first argument is ref, and second is validation rules
register(e, { required: true })
}} />

<button>Submit</button>
</form>
);
}
我尝试在 useEffect 中设置 ref 的焦点,但它不起作用:
useEffect(()=>{
firstNameRef.current.focus();
},[])
输入内部也没有:
<input name="firstName" ref={(e) => {
register(e)
firstNameRef.current = e;
e.focus();
}} />

最佳答案

你在使用 typescript 吗?
如果是这样,更换...const firstNameRef = useRef();和...const firstNameRef = useRef<HTMLInputElement | null>(null);

关于reactjs - 如何使用 React-Hook-Form 设置 ref 焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63796608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com