英文:
setFocus not working with react-hook-form in a dialog component
问题
我在使用react-hook-form的setFocus函数时遇到了问题。我尝试在打开SignInDialog组件时聚焦到一个输入字段(用户名),但没有成功。我尝试了几种方法,包括使用useEffect在打开对话框时调用setFocus,以及将ref属性传递给底层的输入元素,但似乎都不起作用。
这是一个重现问题的代码沙盒链接:https://codesandbox.io/p/sandbox/signindialog-smhpmx?file=%2Fsrc%2FSignInDialog.jsx%3A10%2C14
有人可以帮助我找出问题出在哪里吗?
英文:
I’m having an issue with react-hook-form’s setFocus function. I’m trying to focus an input field (username) in a SignInDialog component when the dialog is opened, but it’s not working. I’ve tried several approaches, including using useEffect to call setFocus when the dialog is opened and forwarding the ref prop to the underlying input element, but nothing seems to work.
Here’s a link to a code sandbox that reproduces the issue: https://codesandbox.io/p/sandbox/signindialog-smhpmx?file=%2Fsrc%2FSignInDialog.jsx%3A10%2C14
Can anyone help me figure out what’s going wrong?
答案1
得分: 0
你的效果钩子立即运行,因为你的 SignInDialog
组件始终被挂载/渲染,但焦点调用无法聚焦到任何东西,因为输入框还没有出现。
你可以向依赖项添加另一个标志,例如:
useEffect(() => {
if (openSignInDialog) {
// 仅添加setTimeout也无效
setTimeout(() => {
setFocus("username");
});
}
}, [setFocus, openSignInDialog]);
但更简单的方法是将 autoFocus
属性直接传递给你的 TextFieldStyled
。
英文:
Your effect hook runs immediately because your SignInDialog
component is always mounted/rendered, but the focus call can't focus anything because the input is not there yet.
You can either add another flag to the deps, for example:
useEffect(() => {
if (openSignInDialog) {
// It also does not work without timeout
setTimeout(() => {
setFocus("username");
});
}
}, [setFocus, openSignInDialog]);
But the easier way would be to just pass autoFocus
props to your TextFieldStyled
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论